/**
 * write_case_report.ts — Case-Writer's primary writer.
 *
 * Saves the Watson-style narrative to case/reports/<slug>.md with bureau
 * frontmatter. Lightweight — no DB row by default; the harvest is the
 * markdown itself. (Future migration could add a public.case_reports table
 * if discoverability via SQL becomes needed.)
 */
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { audit } from "../lib/audit";
import { env } from "../lib/env";

export interface WriteCaseReportArgs {
  topic: string;
  topic_pt_br?: string;
  slug: string;
  body_md: string;
  meta: {
    n_evidence: number;
    n_hypotheses: number;
    n_contradictions: number;
    n_witnesses: number;
    n_outliers: number;
    n_calibrations: number;
  };
}

export interface WriteCaseReportContext {
  job_id: string;
  detective: string;
}

function renderFrontmatter(args: WriteCaseReportArgs, ctx: WriteCaseReportContext): string {
  return [
    "---",
    `schema_version: "0.1.0"`,
    `type: case_report`,
    `topic: ${JSON.stringify(args.topic)}`,
    `topic_pt_br: ${JSON.stringify(args.topic_pt_br ?? args.topic)}`,
    `slug: ${args.slug}`,
    `created_by: ${ctx.detective}`,
    `job_id: ${ctx.job_id}`,
    `created_at: ${new Date().toISOString()}`,
    `n_evidence: ${args.meta.n_evidence}`,
    `n_hypotheses: ${args.meta.n_hypotheses}`,
    `n_contradictions: ${args.meta.n_contradictions}`,
    `n_witnesses: ${args.meta.n_witnesses}`,
    `n_outliers: ${args.meta.n_outliers}`,
    `n_calibrations: ${args.meta.n_calibrations}`,
    "---",
    "",
  ].join("\n");
}

export async function writeCaseReport(
  args: WriteCaseReportArgs,
  ctx: WriteCaseReportContext,
): Promise<{ case_file: string; slug: string }> {
  if (!args.topic?.trim()) throw new Error("topic required");
  if (!args.slug?.match(/^[a-z0-9][a-z0-9-]*$/)) throw new Error(`bad slug: ${args.slug}`);
  if (!args.body_md?.trim()) throw new Error("body_md required");
  if (args.body_md.length < 200) throw new Error("body_md too short (< 200 chars)");

  const dir = path.join(env.CASE_ROOT, "reports");
  await mkdir(dir, { recursive: true });
  const file = path.join(dir, `${args.slug}.md`);
  await writeFile(file, renderFrontmatter(args, ctx) + args.body_md.trimEnd() + "\n", "utf-8");

  await audit({
    event: "write_case_report",
    job_id: ctx.job_id,
    detective: ctx.detective,
    slug: args.slug,
    topic: args.topic.slice(0, 200),
    body_chars: args.body_md.length,
    file,
    ...args.meta,
  });

  return { case_file: file, slug: args.slug };
}
