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

import { inspectWp5TaskLineage } from "../../scripts/lib/wp4-07-gate.mjs";

const sha = (digit) => digit.repeat(40);
const commit = (index) => ({ sha: sha(String(index)), subject: `feat: complete TASK-WP5-0${index}` });

test("WP5 lineage recognizes tasks already merged into later remote heads", () => {
  const gate = inspectWp5TaskLineage({
    "codex/wp5-03": sha("3"),
    "codex/wp5-04": sha("4"),
  }, {
    "codex/wp5-03": [commit(3), commit(2), commit(1)],
    "codex/wp5-04": [commit(4), commit(2), commit(1)],
  });

  assert.equal(gate.complete, false);
  assert.equal(gate.candidate_baseline_branch, "codex/wp5-04");
  assert.deepEqual(gate.missing_tasks, ["TASK-WP5-05", "TASK-WP5-06", "TASK-WP5-07"]);
  assert.equal(gate.task_shas["TASK-WP5-01"], sha("1"));
  assert.equal(gate.task_shas["TASK-WP5-02"], sha("2"));
});

test("WP5 lineage accepts independently pushed terminal branches without rewriting their heads", () => {
  const heads = Object.fromEntries(Array.from({ length: 5 }, (_, index) => [`codex/wp5-0${index + 3}`, sha(String(index + 3))]));
  const histories = {
    "codex/wp5-03": [commit(3), commit(2), commit(1)],
    "codex/wp5-04": [commit(4), commit(2), commit(1)],
    "codex/wp5-05": [commit(5), commit(4), commit(2), commit(1)],
    "codex/wp5-06": [commit(6), commit(5), commit(4), commit(2), commit(1)],
    "codex/wp5-07": [commit(7), commit(4), commit(2), commit(1)],
  };
  const complete = inspectWp5TaskLineage(heads, histories);
  const incomplete = inspectWp5TaskLineage(heads, { ...histories, "codex/wp5-03": [commit(2), commit(1)] });

  assert.equal(complete.complete, true);
  assert.deepEqual(complete.missing_tasks, []);
  assert.deepEqual(complete.terminal_branch_shas, heads);
  assert.equal(incomplete.complete, false);
  assert.deepEqual(incomplete.missing_tasks, ["TASK-WP5-03"]);
});
