/**
 * Renders parsed learning-loop entries into the generated INDEX.md content. The output is a pure
 * function of the entry list: fixed frontmatter (`generated: true`, no `last_reviewed`), a fixed
 * header that points maintainers at `goat-flow index` and `goat-flow stats --check`, and one row
 * per entry in the shared `- [Title](file) (search: "...") - hook` schema. No counts, dates, or
 * other clock-derived values may appear here - `index-fresh` string-compares a regeneration
 * against the on-disk file, so any nondeterminism reads as permanent staleness.
 */
import type { IndexBucket, IndexEntry } from "./parse-bucket.js";

/** H1 title per generated bucket index. */
const BUCKET_TITLES: Record<IndexBucket, string> = {
  footguns: "Footguns Index",
  lessons: "Lessons Index",
  patterns: "Patterns Index",
  decisions: "Decisions Index",
};

/** What one row points at, phrased per bucket so a cold agent knows why it would open the file. */
const BUCKET_ROW_NOUN: Record<IndexBucket, string> = {
  footguns: "one active footgun entry",
  lessons: "one lesson entry",
  patterns: "one pattern entry",
  decisions: "one Architectural Decision Record with its current status",
};

/**
 * Render one generated bucket index from its parsed entries.
 *
 * @param bucket - which learning-loop bucket the index covers; selects title and row description
 * @param entries - parsed active entries in their deterministic parse order
 * @returns full INDEX.md content including frontmatter and a trailing newline
 */
export function formatIndex(
  bucket: IndexBucket,
  entries: IndexEntry[],
): string {
  const header = [
    "---",
    "category: index",
    `bucket: ${bucket}`,
    "generated: true",
    "---",
    "",
    `# ${BUCKET_TITLES[bucket]}`,
    "",
    `Generated by \`goat-flow index\`; do not edit by hand. Each row below maps ${BUCKET_ROW_NOUN[bucket]} to its source file with a grep-friendly \`(search: "...")\` anchor. Re-run \`goat-flow index\` after adding, editing, renaming, or resolving entries - \`goat-flow stats --check\` fails while this file is stale. Live entry counts and freshness come from \`goat-flow stats\`.`,
    "",
  ];
  const rows =
    entries.length === 0
      ? ["_No active entries._"]
      : entries.map(
          (entry) =>
            `- [${entry.title}](${entry.sourceFile}) (search: "${entry.anchor}") - ${entry.hook}`,
        );
  return [...header, ...rows].join("\n") + "\n";
}
