import assert from "node:assert/strict";
import test from "node:test";

import { buildWp706PrefreezeReport } from "../../scripts/lib/wp7-06-prefreeze.mjs";

const expectedTrace = {
  errors: [],
  status: "passed",
  summary: {
    acceptanceCriteria: 52,
    errorCategories: 9,
    featureModules: 13,
    parentFamilies: 89,
    penProductFrames: 18,
    productContracts: 19,
    requirements: 109,
    tasks: 52,
    testCases: 117,
    uiPages: 22,
  },
};

const upstream = {
  "TASK-WP7-01": { branch: "codex/wp7-01", head: "1".repeat(40), merged: true, status: "passed" },
  "TASK-WP7-02": { branch: "codex/wp7-02", head: "2".repeat(40), merged: true, status: "passed" },
  "TASK-WP7-03": { branch: "codex/wp7-03", head: "3".repeat(40), merged: true, status: "deferred_nonblocking_first_version" },
  "TASK-WP7-04": { branch: "codex/wp7-04", head: "4".repeat(40), merged: true, status: "deferred_nonblocking_first_version" },
  "TASK-WP7-05": { branch: "codex/wp7-05", head: "5".repeat(40), merged: true, status: "passed" },
};

test("builds the exact WP7-06 pre-freeze closure without pretending deferred suppliers passed", () => {
  const report = buildWp706PrefreezeReport({
    currentCommit: "a".repeat(40),
    releaseExists: false,
    trace: expectedTrace,
    upstream,
  });

  assert.equal(report.status, "passed");
  assert.equal(report.release_json_written, false);
  assert.deepEqual(report.trace_summary, expectedTrace.summary);
  assert.deepEqual(report.deferred_external_tasks, ["TASK-WP7-03", "TASK-WP7-04"]);
});

test("rejects missing lineage and premature RELEASE.json", () => {
  assert.throws(() => buildWp706PrefreezeReport({
    currentCommit: "a".repeat(40),
    releaseExists: false,
    trace: expectedTrace,
    upstream: { ...upstream, "TASK-WP7-05": { ...upstream["TASK-WP7-05"], merged: false } },
  }), /WP7_06_UPSTREAM_NOT_MERGED:TASK-WP7-05/);

  assert.throws(() => buildWp706PrefreezeReport({
    currentCommit: "a".repeat(40),
    releaseExists: true,
    trace: expectedTrace,
    upstream,
  }), /WP7_06_RELEASE_WRITTEN_PREMATURELY/);
});

test("rejects trace drift and unsupported upstream statuses", () => {
  assert.throws(() => buildWp706PrefreezeReport({
    currentCommit: "a".repeat(40),
    releaseExists: false,
    trace: { ...expectedTrace, summary: { ...expectedTrace.summary, testCases: 116 } },
    upstream,
  }), /WP7_06_TRACE_COUNT_MISMATCH:testCases/);

  assert.throws(() => buildWp706PrefreezeReport({
    currentCommit: "a".repeat(40),
    releaseExists: false,
    trace: expectedTrace,
    upstream: { ...upstream, "TASK-WP7-03": { ...upstream["TASK-WP7-03"], status: "passed" } },
  }), /WP7_06_UNSUPPORTED_STATUS:TASK-WP7-03/);
});
