import { dirname } from "node:path";
import { VIEW_NAMES } from "./constants.js";
import { CliError } from "./errors.js";
import { appendLedgerEvent, ensureDir, projectPath, projectRelative } from "./fs.js";
import { loadIndex, queryIndex, sortRecords } from "./indexer.js";
import { recordReference } from "./records.js";
import { writeFileSync } from "node:fs";

function formatRefs(items) {
  if (items.length === 0) return ["- None"];
  return items.map((item) => `- ${item.id} [${item.status}] ${item.title} (${item.path})`);
}

export function renderMarkdown(project, viewName) {
  const index = loadIndex(project);
  const generatedAt = new Date().toISOString();
  const nextActions = queryIndex(index, "next-actions").slice(0, 10);
  const blocked = queryIndex(index, "blocked").slice(0, 10);
  const missingSpec = queryIndex(index, "missing-spec").slice(0, 10);
  const completionGaps = queryIndex(index, "completion-gaps").slice(0, 10);

  if (viewName === "dashboard") {
    return [
      "<!-- generated by project-ledger; do not edit -->",
      "# Project Ledger Dashboard",
      "",
      `Generated: ${generatedAt}`,
      "",
      `Project: ${index.project.name} (${index.project.id})`,
      "",
      "## Counts",
      "",
      `- Work: ${index.counts.work}`,
      `- Tasks: ${index.counts.task}`,
      `- Attempts: ${index.counts.attempt}`,
      `- Decisions: ${index.counts.decision}`,
      `- Risks: ${index.counts.risk}`,
      `- Issues: ${index.issues.length}`,
      "",
      "## Next Actions",
      "",
      ...formatRefs(nextActions),
      "",
      "## Blocked",
      "",
      ...formatRefs(blocked),
      "",
      "## Missing Spec",
      "",
      ...formatRefs(missingSpec),
      "",
      "## Completion Gaps",
      "",
      ...formatRefs(completionGaps),
      "",
    ].join("\n");
  }

  if (viewName === "handoff") {
    return [
      "<!-- generated by project-ledger; do not edit -->",
      "# Project Ledger Handoff",
      "",
      `Generated: ${generatedAt}`,
      "",
      "## Start Here",
      "",
      "- Run `project-ledger status --json`.",
      "- Run `project-ledger query --kind next-actions --json`.",
      "- Read only referenced source records and specs.",
      "",
      "## Next Actions",
      "",
      ...formatRefs(nextActions),
      "",
      "## Risks And Blockers",
      "",
      ...formatRefs(blocked),
      "",
    ].join("\n");
  }

  if (viewName === "roadmap") {
    const work = index.records.filter((record) => record.kind === "work");
    return [
      "<!-- generated by project-ledger; do not edit -->",
      "# Project Ledger Roadmap",
      "",
      `Generated: ${generatedAt}`,
      "",
      "## Work",
      "",
      ...formatRefs(sortRecords(work).map((record) => recordReference(record))),
      "",
    ].join("\n");
  }

  throw new CliError(`Unsupported render view: ${viewName}`, "invalid_render_view");
}

export function render(project, viewName, options) {
  if (!VIEW_NAMES.includes(viewName)) {
    throw new CliError(`Unsupported render view: ${viewName}`, "invalid_render_view");
  }
  const markdown = renderMarkdown(project, viewName);
  const relPath = `views/${viewName}.md`;
  const path = projectPath(project, relPath);
  const displayPath = projectRelative(project, path);
  if (options.write) {
    ensureDir(dirname(path));
    writeFileSync(path, markdown, "utf8");
    appendLedgerEvent(project, {
      type: "view_rendered",
      view: viewName,
      path: displayPath,
      source: "project-ledger",
    });
  }
  return {
    view: viewName,
    path: displayPath,
    markdown,
    written: Boolean(options.write),
  };
}
