import assert from "node:assert/strict";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";

import { parseMarkdownFrontmatter } from "../../ledger/frontmatter.ts";
import { writeFactCheckReview } from "../writeFactCheckReview.ts";

describe("writeFactCheckReview governance boundary", () => {
  it("records needs_pm as an abstention rather than a human-only decision", async () => {
    const root = await mkdtemp(join(tmpdir(), "codeflowmu-fact-review-"));
    try {
      const result = await writeFactCheckReview({
        projectRoot: root,
        taskId: "TASK-20260810-101",
        reportId: "REPORT-20260810-101-QA-to-PM",
        evidence: {
          session: { found: false },
          files: { read: [], changed: [] },
          commands: [],
          report: { found: true },
          data_queries: [],
          warnings: [],
        },
        result: {
          verdict: "needs_admin",
          review_state: "needs_pm",
          reason_code: "acceptance_contract_needs_pm",
          unsupported_claims: [],
          required_changes: [],
          claims: {
            claimsTestRun: false,
            claimsTestPassed: false,
            claimsDataQuery: false,
            claimsFileChange: false,
            claimsNumericStats: false,
            claimsMarkdownTable: false,
          },
        },
      });
      const raw = await readFile(result.path, "utf-8");
      const fm = parseMarkdownFrontmatter(raw) as Record<string, unknown>;
      assert.equal(fm["decision"], "abstained");
      assert.equal(fm["review_state"], "needs_pm");
      assert.equal(fm["awaiting_pm_decision"], true);
    } finally {
      await rm(root, { recursive: true, force: true });
    }
  });
});
