import { test, expect } from "bun:test";
import { computeSignature, specDigest } from "./kb.ts";

// kb signature invariants — required so the KB's retrieval layer
// doesn't silently drift when we add fields to ScenarioSpec.

test("computeSignature is stable across reorderings of unrelated fields", () => {
  const a = {
    client: "Acme Corp",
    events: [
      { kind: "baseline_fill", role: "Welder", count: 3, city: "Toledo", state: "OH" },
    ],
  };
  const b = { ...a, date: "2026-05-01", contract: { deadline: "2026-05-15" } } as any;
  const c = { ...a, staffer: { id: "S-1", name: "X", tenure_months: 10, role: "senior" } } as any;
  const sigA = computeSignature(a);
  const sigB = computeSignature(b);
  const sigC = computeSignature(c);
  expect(sigA).toBe(sigB);
  expect(sigA).toBe(sigC);
});

test("computeSignature changes when role changes", () => {
  const base = { client: "Acme", events: [{ kind: "baseline_fill", role: "Welder", count: 3, city: "Toledo", state: "OH" }] };
  const swapped = { client: "Acme", events: [{ kind: "baseline_fill", role: "Electrician", count: 3, city: "Toledo", state: "OH" }] };
  expect(computeSignature(base)).not.toBe(computeSignature(swapped));
});

test("computeSignature changes when city or count changes", () => {
  const base = { client: "A", events: [{ kind: "baseline_fill", role: "Welder", count: 3, city: "Toledo", state: "OH" }] };
  const cityChange = { ...base, events: [{ ...base.events[0], city: "Detroit", state: "MI" }] };
  const countChange = { ...base, events: [{ ...base.events[0], count: 5 }] };
  expect(computeSignature(base)).not.toBe(computeSignature(cityChange));
  expect(computeSignature(base)).not.toBe(computeSignature(countChange));
});

test("specDigest includes each event's role + city", () => {
  const spec = {
    client: "Acme",
    events: [
      { kind: "baseline_fill", role: "Welder", count: 3, city: "Toledo", state: "OH" },
      { kind: "emergency", role: "Loader", count: 2, city: "Chicago", state: "IL" },
    ],
  };
  const digest = specDigest(spec);
  expect(digest).toContain("Acme");
  expect(digest).toContain("Welder");
  expect(digest).toContain("Toledo,OH");
  expect(digest).toContain("Loader");
  expect(digest).toContain("Chicago,IL");
});
