#!/usr/bin/env bun
/**
 * bundle_help.ts — generate `_shared/mcp-tools/get-help-content.ts` from
 * the canonical `AGENT_QUICK_REFERENCE.md`.
 *
 * Runs on demand whenever `AGENT_QUICK_REFERENCE.md` changes. The output
 * file is checked in so the MCP server doesn't need filesystem access to
 * the repo at runtime — the bundled content travels with `@cerefox/memory`
 * and inside the `cerefox-mcp` Edge Function deploy.
 *
 * Companion CI check: `scripts/check_help_bundle.ts` re-runs this emitter
 * in-memory and diffs against the on-disk output. Fails if they diverge,
 * which means someone edited `AGENT_QUICK_REFERENCE.md` but forgot to
 * rerun `bun scripts/bundle_help.ts`.
 *
 * Layer 3 of the MCP discoverability response — see
 * `docs/specs/polish-and-distribution-design.md` §10d.
 */

import { readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
const SOURCE = join(REPO_ROOT, "AGENT_QUICK_REFERENCE.md");
const OUTPUT = join(REPO_ROOT, "_shared", "mcp-tools", "get-help-content.ts");

interface Section {
  heading: string;
  body: string; // includes the heading line
}

function parseSections(content: string): Section[] {
  const lines = content.split("\n");
  const sections: Section[] = [];
  let currentHeading: string | null = null;
  let currentLines: string[] = [];

  function flush() {
    if (currentHeading !== null) {
      sections.push({ heading: currentHeading, body: currentLines.join("\n").trim() });
    }
  }

  for (const line of lines) {
    const m = line.match(/^## (.+)/);
    if (m) {
      flush();
      currentHeading = m[1].trim();
      currentLines = [line];
    } else if (currentHeading !== null) {
      currentLines.push(line);
    }
  }
  flush();
  return sections;
}

function emit(content: string, sections: Section[]): string {
  const entries = sections
    .map((s) => `  ${JSON.stringify(s.heading)}: ${JSON.stringify(s.body)}`)
    .join(",\n");

  return `/**
 * GENERATED FILE — do not edit by hand.
 *
 * Generated by \`bun scripts/bundle_help.ts\` from AGENT_QUICK_REFERENCE.md.
 * Re-run after editing the source file. CI's \`scripts/check_help_bundle.ts\`
 * fails if this file diverges from the source.
 *
 * Bundled into both \`@cerefox/memory\` and the \`cerefox-mcp\` Edge Function
 * so the \`cerefox_get_help\` MCP tool can return content without filesystem
 * access. Layer 3 of the MCP discoverability response — see
 * docs/specs/polish-and-distribution-design.md §10d.
 */

export const HELP_FULL = ${JSON.stringify(content)};

/** Sections keyed by their H2 heading text (lower-cased for matching). */
export const HELP_SECTIONS: Record<string, string> = {
${entries},
};

export const HELP_SECTION_HEADINGS: string[] = [${sections
    .map((s) => JSON.stringify(s.heading))
    .join(", ")}];
`;
}

function main(): void {
  const content = readFileSync(SOURCE, "utf8");
  const sections = parseSections(content);
  const output = emit(content, sections);
  writeFileSync(OUTPUT, output, "utf8");
  console.log(
    `✓ Wrote ${OUTPUT.replace(REPO_ROOT + "/", "")} ` +
      `(${content.length} chars, ${sections.length} sections).`,
  );
}

main();
