import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

import { addSpecific, emptyBank, loadBank, recordUsage, saveBank, specificId } from "../src/bank.js";
import { boundSpecificIds } from "../src/binding.js";
import type { LivedSpecifics } from "../src/binding.js";
import type { Bank } from "../src/types.js";

const tmp = () => mkdtempSync(join(tmpdir(), "specifics-usage-"));

const CONTENT = {
  a: "Vi målte 40 prosent kortere ledetid etter omleggingen.",
  b: "Kunden avlyste pilotene fordi ingen eide dataene.",
};

function bankWith(...contents: string[]): Bank {
  let bank = emptyBank();
  for (const content of contents) {
    bank = addSpecific(bank, {
      type: "number",
      content,
      topicTags: ["ai"],
      provenance: { capturedAt: "2026-06-20", source: "test" },
    }).bank;
  }
  return bank;
}

describe("specifics-bank — usage logging (N11: «used in edition NN»)", () => {
  test("recording usage stamps the edition on the specific", () => {
    const bank = bankWith(CONTENT.a);
    const id = specificId(CONTENT.a);

    const res = recordUsage(bank, { ids: [id], editionId: "seres/05" });

    assert.deepEqual(res.recorded, [id]);
    assert.deepEqual(res.alreadyRecorded, []);
    assert.deepEqual(res.unknown, []);
    assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
  });

  test("recording the same edition twice is idempotent (a re-lock does not double-count)", () => {
    const bank = bankWith(CONTENT.a);
    const id = specificId(CONTENT.a);

    const once = recordUsage(bank, { ids: [id], editionId: "seres/05" });
    const twice = recordUsage(once.bank, { ids: [id], editionId: "seres/05" });

    assert.deepEqual(twice.recorded, []);
    assert.deepEqual(twice.alreadyRecorded, [id]);
    assert.deepEqual(twice.bank.specifics[0].usedIn, ["seres/05"]);
  });

  test("a second edition appends, preserving order", () => {
    const bank = bankWith(CONTENT.a);
    const id = specificId(CONTENT.a);

    const first = recordUsage(bank, { ids: [id], editionId: "seres/05" });
    const second = recordUsage(first.bank, { ids: [id], editionId: "seres/06" });

    assert.deepEqual(second.bank.specifics[0].usedIn, ["seres/05", "seres/06"]);
  });

  test("an id absent from the bank is reported as unknown, not silently dropped", () => {
    const bank = bankWith(CONTENT.a);
    const res = recordUsage(bank, { ids: [specificId(CONTENT.a), "deadbeef1234"], editionId: "seres/05" });

    assert.deepEqual(res.unknown, ["deadbeef1234"]);
    assert.deepEqual(res.recorded, [specificId(CONTENT.a)]);
  });

  test("archived material still records use — the use is historical fact", () => {
    let bank = emptyBank();
    bank = addSpecific(bank, {
      type: "named-case",
      content: CONTENT.b,
      topicTags: ["ai"],
      provenance: { capturedAt: "2026-06-20", source: "test" },
      status: "archived",
    }).bank;

    const res = recordUsage(bank, { ids: [specificId(CONTENT.b)], editionId: "seres/05" });
    assert.deepEqual(res.recorded, [specificId(CONTENT.b)]);
    assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
  });

  test("recording touches only the named specifics", () => {
    const bank = bankWith(CONTENT.a, CONTENT.b);
    const res = recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: "seres/05" });

    assert.deepEqual(res.bank.specifics[0].usedIn, ["seres/05"]);
    assert.equal(res.bank.specifics[1].usedIn, undefined);
  });

  test("an empty id list is a no-op, not an error", () => {
    const bank = bankWith(CONTENT.a);
    const res = recordUsage(bank, { ids: [], editionId: "seres/05" });
    assert.deepEqual(res.recorded, []);
    assert.equal(res.bank.specifics[0].usedIn, undefined);
  });

  test("a blank edition id throws — an unattributable use is worse than none", () => {
    const bank = bankWith(CONTENT.a);
    assert.throws(() => recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: "  " }), /editionId/);
  });

  test("usedIn survives a save/load round-trip; an untouched bank stays field-free", () => {
    const dir = tmp();
    try {
      const path = join(dir, "specifics-bank.json");
      const bank = bankWith(CONTENT.a, CONTENT.b);
      const res = recordUsage(bank, { ids: [specificId(CONTENT.a)], editionId: "seres/05" });
      saveBank(path, res.bank);

      const back = loadBank(path);
      assert.deepEqual(back.specifics[0].usedIn, ["seres/05"]);
      // additive-optional: never-used material carries no field at all (schema stays v1)
      assert.equal("usedIn" in back.specifics[1], false);
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});

describe("specifics-bank — boundSpecificIds (what an edition actually consumed)", () => {
  const ls = (slots: LivedSpecifics["slots"]): LivedSpecifics => ({ slots, status: "bound" });

  test("extracts the ids of specific-bound slots only", () => {
    const res = boundSpecificIds(
      ls([
        { slotId: "kp1", kind: "key-point", label: "a", binding: { type: "specific", specificId: "aaa111" } },
        { slotId: "kp2", kind: "key-point", label: "b", binding: { type: "abstrakt", rationale: "bevisst" } },
        { slotId: "kp3", kind: "section", label: "c", binding: { type: "ekstern", source: "https://x" } },
        { slotId: "kp4", kind: "section", label: "d", binding: { type: "unresolved" } },
      ]),
    );
    assert.deepEqual(res, ["aaa111"]);
  });

  test("dedupes an id bound in several slots", () => {
    const res = boundSpecificIds(
      ls([
        { slotId: "kp1", kind: "key-point", label: "a", binding: { type: "specific", specificId: "aaa111" } },
        { slotId: "kp2", kind: "section", label: "b", binding: { type: "specific", specificId: "aaa111" } },
        { slotId: "kp3", kind: "section", label: "c", binding: { type: "specific", specificId: "bbb222" } },
      ]),
    );
    assert.deepEqual(res, ["aaa111", "bbb222"]);
  });

  test("an empty slot map yields no ids", () => {
    assert.deepEqual(boundSpecificIds(ls([])), []);
  });
});
