---
import DocsLayout from "../../layouts/DocsLayout.astro";
import { getCollection } from "astro:content";

const base = import.meta.env.BASE_URL.replace(/\/$/, "");
const QUICK_START = `${base}/docs/setup/install-recipes`;
const OVERVIEW = `${base}/docs/index`;

// Internal governance drafts that should not appear on the public site.
const HIDDEN_DOCS = new Set(["board-resolution-draft"]);

const all = (await getCollection("docs")).filter(
  (entry) => !HIDDEN_DOCS.has(entry.id.replace(/\.md$/, "")),
);

// First markdown H1 of a page body (skipping doctoc/SPDX HTML comments) — used
// to give RFC entries their full descriptive titles.
const firstH1 = (body: string | undefined): string | null => {
  const m = (body ?? "").replace(/<!--[\s\S]*?-->/g, "").match(/^#\s+(.+?)\s*$/m);
  return m ? m[1].trim() : null;
};

type DocItem = { slug: string; label: string; description?: string };
type Group = { items: DocItem[]; overview?: string; overviewBody?: string };
const groups = new Map<string, Group>();
// Sub-sections nested under another group's directory but surfaced as their
// own section (keyed by two-segment path). Mirrors DocsLayout's sidebar.
const NESTED_GROUPS = new Set(["education/training"]);
for (const entry of all) {
  const parts = entry.id.split("/");
  const two = parts.slice(0, 2).join("/");
  const key = NESTED_GROUPS.has(two)
    ? two
    : parts.length > 1
      ? parts[0]
      : "_root";
  const slug = entry.id.replace(/\.md$/, "");
  const leaf = parts[parts.length - 1].replace(/\.md$/, "");
  const isReadme = /^(readme|index)$/i.test(leaf);
  // A section's own README/index (the one sitting directly in the section's
  // directory) is its overview; deeper READMEs — tools/<name>/readme — are
  // normal items.
  const dir = parts.slice(0, -1).join("/") || "_root";
  const isGroupOverview = isReadme && dir === key;

  if (!groups.has(key)) groups.set(key, { items: [] });
  const group = groups.get(key)!;

  if (isGroupOverview) {
    // Hoist the overview onto the section heading instead of listing it, and
    // keep its body so we can order the section's pages the way the overview
    // (the section's own README/table of contents) presents them.
    group.overview = slug;
    group.overviewBody = entry.body;
    continue;
  }

  // Match the sidebar navigation: tool pages are labelled by tool name; RFCs
  // get their full H1 title; everything else uses its title / prettified slug.
  const label =
    key === "tools"
      ? (parts[1] ?? leaf)
      : key === "rfcs"
        ? (entry.data.title ?? firstH1(entry.body) ?? leaf.replace(/-/g, " "))
        : entry.data.title ?? leaf.replace(/-/g, " ");
  group.items.push({ slug, label, description: entry.data.description });
}

// Friendly names + one-line summaries for each docs group.
const GROUP_META: Record<string, { name: string; blurb: string }> = {
  _root: {
    name: "Overview & concepts",
    blurb:
      "What Magpie is, how it works, and the cross-cutting concepts — modes, design principles, confidentiality, labels, and editorial guidelines.",
  },
  education: {
    name: "Education",
    blurb:
      "The maintainer-education stream — a step-by-step path to building and running agents for your project: what agents are, working with them, writing and evaluating your first skill, English as code, and contributing back, plus a pattern catalogue and hands-on tutorials.",
  },
  "education/training": {
    name: "Training",
    blurb:
      "An LMS-neutral Apache Training module that wraps the education stream as a structured course — one lesson per progression page, each adding learning objectives, exercises, and self-check questions.",
  },
  setup: {
    name: "Setup",
    blurb:
      "Adopt Magpie in your repo and run agents safely — install recipes, prerequisites, sandboxing, privacy/LLM routing, and unadopting.",
  },
  security: {
    name: "Security",
    blurb:
      "The security-issue lifecycle — process, roles, forwarder routing policy, onboarding, and the threat model. Maintainer-only.",
  },
  "pr-management": {
    name: "PR management",
    blurb: "Maintainer-facing PR-queue triage, stats, and deep code review.",
  },
  "issue-management": {
    name: "Issue management",
    blurb:
      "Issue triage, bug reproduction, fix drafting, and backlog re-assessment.",
  },
  mentoring: {
    name: "Mentoring",
    blurb: "Contributor mentoring — the spec, tone guide, and first skills.",
  },
  "contributor-growth": {
    name: "Contributor growth",
    blurb:
      "The contributor-to-committer path — welcoming, activity tracking, and nomination evidence.",
  },
  "repo-health": {
    name: "Repo health",
    blurb:
      "Read-only maintenance audits — CI, dependencies, licenses, and flaky tests.",
  },
  pairing: {
    name: "Pairing",
    blurb: "Developer-side skills you run in your own dev loop.",
  },
  "release-management": {
    name: "Release management",
    blurb: "The ASF release lifecycle — plan, cut, vote, promote, announce.",
  },
  utilities: {
    name: "Utilities",
    blurb: "Framework meta-skills — author skills and list every skill.",
  },
  adapters: {
    name: "Adapters",
    blurb:
      "Authoring adapters and the discovery registry of in-tree and external backends.",
  },
  tools: {
    name: "Tools",
    blurb:
      "Every framework tool — the contract or substrate it provides, with per-tool docs.",
  },
  rfcs: {
    name: "RFCs",
    blurb: "Design proposals under discussion.",
  },
};

const ORDER = [
  "_root",
  "education",
  "education/training",
  "setup",
  "pr-management",
  "issue-management",
  "mentoring",
  "contributor-growth",
  "repo-health",
  "pairing",
  "release-management",
  "security",
  "utilities",
  "adapters",
  "tools",
  "rfcs",
];

// Position of a page within its section's overview: the character offset of the
// first link to that page in the overview README (which, via its "what you can
// learn" table / table of contents, lists pages in the intended reading order).
// Pages the overview doesn't link get -1 and fall back to alphabetical, after
// the linked ones. The negative-lookahead stops a slug matching a longer one
// (e.g. `.../agentic-work` must not match `.../agentic-work-plus`).
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const overviewOrder = (body: string | undefined, slug: string): number => {
  if (!body) return -1;
  return body.search(new RegExp(`docs/${escapeRe(slug)}(?![\\w-])`));
};

const sortedGroups = Array.from(groups.entries())
  .map(([key, group]) => ({
    key,
    meta: GROUP_META[key] ?? {
      name: key
        .replace(/-/g, " ")
        .replace(/\b\w/g, (c) => c.toUpperCase()),
      blurb: "",
    },
    overview: group.overview,
    items: group.items
      .map((item) => ({
        ...item,
        order: overviewOrder(group.overviewBody, item.slug),
      }))
      .sort((a, b) => {
        // README reading order first; unlinked pages (order -1) sort last,
        // alphabetically among themselves — the previous default everywhere.
        const an = a.order === -1 ? Infinity : a.order;
        const bn = b.order === -1 ? Infinity : b.order;
        return an - bn || a.label.localeCompare(b.label);
      }),
  }))
  .sort((a, b) => {
    const ai = ORDER.indexOf(a.key);
    const bi = ORDER.indexOf(b.key);
    return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi);
  });

const totalPages = all.length;
---

<DocsLayout title="Documentation" currentSlug="" editUrl="https://github.com/apache/magpie-site/edit/main/src/pages/docs/index.astro">
  <h1>Apache Magpie™ Documentation</h1>
  <p>
    Apache Magpie is an AI assistant for open-source project maintainers. It
    handles the repetitive parts of running a project — triaging issues,
    reviewing PRs, onboarding contributors, managing security reports, cutting
    releases — so maintainers can spend their time on the work that needs a
    human. <strong>The agent proposes; the human decides.</strong>
  </p>

  <h2>Quick Start</h2>
  <p>
    Adopt Magpie in your repo with a single copy-pasteable bootstrap, then let
    the <code>setup</code> skill wire up the rest. Pick an install method and
    follow the verbatim recipe:
  </p>
  <p>
    <a href={QUICK_START}><strong>⚡ Quick Start → Install recipes</strong></a>
    &nbsp;·&nbsp;
    <a href={`${base}/docs/prerequisites`}>Prerequisites</a>
    &nbsp;·&nbsp;
    <a href={OVERVIEW}>What is Apache Magpie?</a>
    &nbsp;·&nbsp;
    <a href={`${base}/architecture`}>Architecture</a>
  </p>

  <h2>Explore the docs</h2>
  <p>
    {totalPages} pages, synced from{" "}
    <a href="https://github.com/apache/magpie/tree/main/docs">apache/magpie/docs</a>{" "}
    and grouped by area. Every page is also in the sidebar.
  </p>

  {sortedGroups.map((group) => (
    <section>
      <h3>
        {group.overview ? (
          <a href={`${base}/docs/${group.overview}`}>{group.meta.name}</a>
        ) : (
          group.meta.name
        )}
      </h3>
      {group.meta.blurb && <p>{group.meta.blurb}</p>}
      <ul>
        {group.items.map((item) => (
          <li>
            <a class="capitalize" href={`${base}/docs/${item.slug}`}>{item.label}</a>
            {item.description ? ` — ${item.description}` : ""}
          </li>
        ))}
      </ul>
    </section>
  ))}
</DocsLayout>
