import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

import { foldUserProfile } from "../src/profile.js";
import { mintEntityId } from "../src/id.js";
import type { ProfileDoc } from "../src/types.js";

const here = dirname(fileURLToPath(import.meta.url));
const TEMPLATE = readFileSync(join(here, "../../../config/user-profile.template.md"), "utf8");
const POPULATED = readFileSync(join(here, "../fixtures/user-profile.populated.md"), "utf8");

const D1 = "2026-06-23";
const D2 = "2026-07-01";

/** Look a fact up by its source label via the canonical id. */
const byLabel = (doc: ProfileDoc, label: string) =>
  doc.static.find((f) => f.id === mintEntityId({ kind: "profile-field", key: label }));

const FIELD_COUNT = 27; // 22 P1 labeled scalars + 5 P2 expertise areas

describe("foldUserProfile (SC3)", () => {
  describe("SC3a — source-absent", () => {
    const doc = foldUserProfile({ templateText: TEMPLATE, today: D1 });

    test("lists every template field (22 P1 + 5 P2), no dynamic facts", () => {
      assert.equal(doc.static.length, FIELD_COUNT);
      assert.equal(doc.dynamic.length, 0);
    });

    test("placeholder fields fold to an empty value", () => {
      assert.equal(byLabel(doc, "Name")?.value, "");
      assert.equal(byLabel(doc, "Current Role")?.value, "");
      assert.equal(byLabel(doc, "expertise-area-1")?.value, "");
      assert.equal(byLabel(doc, "Follower count")?.value, "");
      assert.equal(byLabel(doc, "Topics to AVOID")?.value, "");
    });

    test("the lone literal template field (Disclaimer) keeps its boilerplate", () => {
      assert.equal(byLabel(doc, "Important Disclaimer")?.value.startsWith("All articles"), true);
    });

    test("deferred Research-Tooling prose does not leak in as fields", () => {
      assert.equal(byLabel(doc, "Always-available floor (no MCP needed)"), undefined);
      assert.equal(byLabel(doc, "Preferred order (optional)"), undefined);
    });

    test("every folded fact has the canonical shape", () => {
      for (const f of doc.static) {
        assert.match(f.id, /^[0-9a-f]{12}$/);
        assert.equal(f.provenance, "human");
        assert.equal(f.status, "active");
        assert.equal(f.evidence_count, 0);
        assert.equal(f.first_seen, D1);
        assert.equal(f.last_seen, D1);
      }
    });
  });

  describe("SC3b — populated (lossless)", () => {
    const doc = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, today: D1 });

    test("same field-set size — fold neither drops nor invents fields", () => {
      assert.equal(doc.static.length, FIELD_COUNT);
    });

    test("every filled value is carried (none dropped)", () => {
      assert.equal(doc.static.every((f) => f.value !== ""), true);
    });

    test("specific filled values land on the right fields", () => {
      assert.equal(byLabel(doc, "Name")?.value, "Jordan Avery");
      assert.equal(byLabel(doc, "Current Role")?.value, "Senior Data Engineer");
      assert.equal(byLabel(doc, "expertise-area-1")?.value, "Streaming data pipelines");
      assert.equal(byLabel(doc, "expertise-area-5")?.value, "Team data literacy");
      assert.equal(byLabel(doc, "Topics to AVOID")?.value, "Crypto");
      assert.equal(byLabel(doc, "Follower count")?.value, "2,400");
      assert.equal(byLabel(doc, "Phrases you commonly use")?.value, '"ship the boring thing"');
    });
  });

  describe("SC3c — idempotent re-run", () => {
    test("re-running source-absent over its own output changes nothing", () => {
      const a = foldUserProfile({ templateText: TEMPLATE, today: D1 });
      const a2 = foldUserProfile({ templateText: TEMPLATE, existing: a, today: D1 });
      assert.deepEqual(a2, a);
    });

    test("re-running populated over its own output changes nothing (no dup)", () => {
      const b = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, today: D1 });
      const b2 = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, existing: b, today: D1 });
      assert.deepEqual(b2, b);
      assert.equal(b2.static.length, FIELD_COUNT);
    });

    test("a later run bumps last_seen but preserves first_seen and value", () => {
      const b = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, today: D1 });
      const later = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, existing: b, today: D2 });
      const name = byLabel(later, "Name");
      assert.equal(name?.first_seen, D1);
      assert.equal(name?.last_seen, D2);
      assert.equal(name?.value, "Jordan Avery");
    });

    test("re-folding source-absent over a populated existing never wipes a filled value", () => {
      const b = foldUserProfile({ templateText: TEMPLATE, instanceText: POPULATED, today: D1 });
      const over = foldUserProfile({ templateText: TEMPLATE, existing: b, today: D2 });
      assert.equal(byLabel(over, "Name")?.value, "Jordan Avery");
    });
  });
});
