import fs from "node:fs/promises";
import path from "node:path";

export interface Chapter { slug: string; order: number; title: string; summary: string; body: string }

const dir = path.join(process.cwd(), "content", "handbook");

function parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {
  const m = raw.match(/^---\n([\s\S]*?)\n---\n?/);
  if (!m) return { data: {}, body: raw };
  const data: Record<string, string> = {};
  for (const line of m[1].split("\n")) {
    const i = line.indexOf(":");
    if (i > 0) data[line.slice(0, i).trim()] = line.slice(i + 1).trim();
  }
  return { data, body: raw.slice(m[0].length) };
}

export async function getChapters(): Promise<Chapter[]> {
  const files = (await fs.readdir(dir)).filter((f) => f.endsWith(".md")).sort();
  return Promise.all(
    files.map(async (f) => {
      const raw = await fs.readFile(path.join(dir, f), "utf8");
      const { data, body } = parseFrontmatter(raw);
      const order = parseInt(f.slice(0, 2), 10) || 0;
      return { slug: f.replace(/^\d+-/, "").replace(/\.md$/, ""), order, title: data.title ?? f, summary: data.summary ?? "", body };
    }),
  );
}

export async function getChapter(slug: string) {
  return (await getChapters()).find((c) => c.slug === slug) ?? null;
}
