/**
 * Gitea Activity Data
 * Fetches commits and repos from self-hosted Gitea instance
 */

import EleventyFetch from "@11ty/eleventy-fetch";

const GITEA_URL = process.env.GITEA_INTERNAL_URL || process.env.GITEA_URL || "https://gitea.giersig.eu";
const GITEA_ORG = process.env.GITEA_ORG || "giersig.eu";
const GITEA_REPOS = (process.env.GITEA_REPOS || "indiekit-blog,indiekit-server").split(",").filter(Boolean);

function truncate(text, maxLength = 80) {
  if (!text || text.length <= maxLength) return text || "";
  return text.slice(0, maxLength - 1) + "...";
}

async function fetchGiteaCommits() {
  const allCommits = [];

  for (const repo of GITEA_REPOS) {
    try {
      const url = `${GITEA_URL}/api/v1/repos/${GITEA_ORG}/${repo}/commits?limit=15`;
      console.log(`[giteaActivity] Fetching commits: ${url}`);
      const commits = await EleventyFetch(url, { duration: "15m", type: "json" });

      for (const c of Array.isArray(commits) ? commits : []) {
        const msg = (c.commit?.message || "").split("\n")[0];
        allCommits.push({
          sha: c.sha.slice(0, 7),
          message: truncate(msg),
          url: c.html_url,
          repo: `${GITEA_ORG}/${repo}`,
          repoUrl: `${GITEA_URL}/${GITEA_ORG}/${repo}`,
          date: c.created || c.commit?.author?.date,
        });
      }
    } catch (e) {
      console.log(`[giteaActivity] Commits fetch failed for ${repo}: ${e.message}`);
    }
  }

  return allCommits.sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 10);
}

async function fetchGiteaFeatured() {
  try {
    const url = `${GITEA_URL}/api/v1/orgs/${GITEA_ORG}/repos?limit=10&sort=newest`;
    const repos = await EleventyFetch(url, { duration: "15m", type: "json" });

    return (Array.isArray(repos) ? repos : [])
      .filter((r) => !r.fork && !r.private)
      .slice(0, 5)
      .map((r) => ({
        fullName: r.full_name,
        name: r.name,
        description: r.description,
        url: r.html_url,
        stars: r.stars_count || r.stargazers_count || 0,
        forks: r.forks_count || 0,
        language: r.language,
      }));
  } catch (e) {
    console.log(`[giteaActivity] Featured fetch failed: ${e.message}`);
    return [];
  }
}

export default async function () {
  try {
    console.log("[giteaActivity] Fetching Gitea data...");

    const [commits, featured] = await Promise.all([
      fetchGiteaCommits(),
      fetchGiteaFeatured(),
    ]);

    return {
      commits,
      stars: [],
      contributions: [],
      featured,
      source: "gitea",
    };
  } catch (error) {
    console.error("[giteaActivity] Error:", error.message);
    return {
      commits: [],
      stars: [],
      contributions: [],
      featured: [],
      source: "error",
    };
  }
}
