import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, renameSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

import { SCHEMA_VERSION } from "../src/types.js";

// Resolve the package root (scripts/trends) so the subprocess `src/cli.ts` path + the
// `tsx` loader resolve regardless of the runner's cwd.
const trendsDir = fileURLToPath(new URL("..", import.meta.url));

function run(args: string[], input: string): { status: number | null; stdout: string } {
  const res = spawnSync("node", ["--import", "tsx", "src/cli.ts", ...args], {
    input,
    encoding: "utf8",
    cwd: trendsDir,
  });
  return { status: res.status, stdout: res.stdout };
}

describe("trends CLI — normalize/score subcommands (RE-R1 / Step 4)", () => {
  describe("normalize (stdin JSON in, JSON out)", () => {
    test("happy path: a JSON batch on stdin -> exit 0 + {items,errors} JSON", () => {
      const batch = JSON.stringify([
        { source: "tavily", title: "Good", url: "https://example.com/a", topics: ["AI", "ai"] },
        { source: "tavily", title: "", url: "https://example.com/b", topics: ["x"] }, // bad: empty title
      ]);
      const { status, stdout } = run(["normalize"], batch);
      assert.equal(status, 0);
      const out = JSON.parse(stdout);
      assert.equal(out.items.length, 1);
      assert.deepEqual(out.items[0].topics, ["ai"]); // deduped + lowercased
      assert.equal(out.errors.length, 1);
      assert.equal(out.errors[0].index, 1);
    });

    test("bad invocation: unparseable stdin -> exit 2", () => {
      const { status } = run(["normalize"], "not json at all");
      assert.equal(status, 2);
    });
  });

  describe("score (stdin JSON in, JSON out)", () => {
    test("happy path: scored candidates on stdin -> exit 0 + {kept,dropped} JSON", () => {
      const candidates = JSON.stringify([
        { id: "high", scores: { pillar: 8, audience: 8, timing: 8, angle: 8, authority: 8 } }, // 8.0
        { id: "low", scores: { pillar: 2, audience: 2, timing: 2, angle: 2, authority: 2 } }, // 2.0
      ]);
      const { status, stdout } = run(["score", "--mode", "kortform", "--threshold", "4.0"], candidates);
      assert.equal(status, 0);
      const out = JSON.parse(stdout);
      assert.deepEqual(
        out.kept.map((k: { id: string }) => k.id),
        ["high"],
      );
      assert.equal(out.kept[0].composite, 8.0);
      assert.equal(out.kept[0].band.priority, "Immediate");
      assert.deepEqual(
        out.dropped.map((d: { id: string }) => d.id),
        ["low"],
      );
    });

    test("bad invocation: an unknown --mode -> exit 2", () => {
      const candidates = JSON.stringify([
        { id: "x", scores: { pillar: 5, audience: 5, timing: 5, angle: 5, authority: 5 } },
      ]);
      const { status } = run(["score", "--mode", "bogus"], candidates);
      assert.equal(status, 2);
    });
  });

  describe("capture (stdin raw item|batch -> folds into the store) (RE-R2a / Step 4)", () => {
    const tmpStore = () => join(mkdtempSync(join(tmpdir(), "trends-capture-")), "trends.json");

    test("happy path: a valid item piped in -> folded into the store, added:1, publishedAt persisted", () => {
      const store = tmpStore();
      try {
        const batch = JSON.stringify([
          {
            source: "tavily",
            title: "Captured",
            url: "https://example.com/c",
            topics: ["ai"],
            publishedAt: "2026-06-20",
          },
        ]);
        const { status, stdout } = run(["capture", "--store", store, "--json"], batch);
        assert.equal(status, 0);
        const summary = JSON.parse(stdout);
        assert.equal(summary.added, 1);
        assert.equal(summary.errors.length, 0);
        assert.equal(
          summary.added + summary.merged + summary.duplicates + summary.errors.length,
          1,
          "tally must sum to the input size",
        );
        const persisted = JSON.parse(readFileSync(store, "utf8"));
        assert.equal(persisted.schemaVersion, SCHEMA_VERSION);
        assert.equal(persisted.trends.length, 1);
        assert.equal(persisted.trends[0].publishedAt, "2026-06-20");
        assert.match(persisted.trends[0].capturedAt, /^\d{4}-\d{2}-\d{2}$/);
        assert.notEqual(
          persisted.trends[0].capturedAt,
          persisted.trends[0].publishedAt,
          "capturedAt (when WE saw it) must be distinct from publishedAt (source date)",
        );
      } finally {
        rmSync(join(store, ".."), { recursive: true, force: true });
      }
    });

    test("a batch with one content-invalid item -> valid added, invalid in errors[], exit 0", () => {
      const store = tmpStore();
      try {
        const batch = JSON.stringify([
          { source: "tavily", title: "Valid", url: "https://example.com/v", topics: ["x"] },
          { title: "no source or url" },
        ]);
        const { status, stdout } = run(["capture", "--store", store, "--json"], batch);
        assert.equal(status, 0);
        const summary = JSON.parse(stdout);
        assert.equal(summary.added, 1);
        assert.equal(summary.errors.length, 1);
        assert.equal(
          summary.added + summary.merged + summary.duplicates + summary.errors.length,
          2,
        );
      } finally {
        rmSync(join(store, ".."), { recursive: true, force: true });
      }
    });

    test("re-capturing the same trend with a new topic -> merged:1, tally still sums", () => {
      const store = tmpStore();
      try {
        const item = (topics: string[]) =>
          JSON.stringify([{ source: "tavily", title: "Dup", url: "https://example.com/d", topics }]);
        run(["capture", "--store", store, "--json"], item(["a"]));
        const { status, stdout } = run(["capture", "--store", store, "--json"], item(["a", "b"]));
        assert.equal(status, 0);
        const summary = JSON.parse(stdout);
        assert.equal(summary.added, 0);
        assert.equal(summary.merged, 1);
        assert.equal(summary.duplicates, 0);
        assert.equal(
          summary.added + summary.merged + summary.duplicates + summary.errors.length,
          1,
        );
      } finally {
        rmSync(join(store, ".."), { recursive: true, force: true });
      }
    });

    test("bad invocation: empty stdin -> exit 2", () => {
      const { status } = run(["capture"], "");
      assert.equal(status, 2);
    });

    // ── RE-R3a: capture persists the computed relevance score (SC7) ──
    test("a valid per-item score -> record carries the computed composite/priority (read back via list --json)", () => {
      const store = tmpStore();
      try {
        const batch = JSON.stringify([
          {
            source: "tavily",
            title: "Scored capture",
            url: "https://example.com/sc",
            topics: ["ai"],
            score: { mode: "kortform", dimensions: { pillar: 9, audience: 8, timing: 9, angle: 7, authority: 6 } },
          },
        ]);
        const cap = run(["capture", "--store", store, "--json"], batch);
        assert.equal(cap.status, 0);
        const summary = JSON.parse(cap.stdout);
        assert.equal(summary.added, 1);
        assert.equal(summary.errors.length, 0);

        const ls = run(["list", "--store", store, "--json"], "");
        assert.equal(ls.status, 0);
        const rows = JSON.parse(ls.stdout);
        assert.equal(rows.length, 1);
        // 9*.30 + 8*.25 + 9*.20 + 7*.15 + 6*.10 = 8.15 -> round1 8.1 (8.15*10 = 81.4999… in IEEE-754) -> Immediate
        assert.equal(rows[0].score.composite, 8.1);
        assert.equal(rows[0].score.priority, "Immediate");
        assert.equal(rows[0].score.mode, "kortform");
        assert.deepEqual(rows[0].score.dimensions, { pillar: 9, audience: 8, timing: 9, angle: 7, authority: 6 });
      } finally {
        rmSync(join(store, ".."), { recursive: true, force: true });
      }
    });

    test("a batch with one bad score (timing:99) -> that item in errors[], the valid one added, exit 0", () => {
      const store = tmpStore();
      try {
        const batch = JSON.stringify([
          {
            source: "tavily",
            title: "Good scored",
            url: "https://example.com/good",
            topics: ["ai"],
            score: { mode: "kortform", dimensions: { pillar: 8, audience: 7, timing: 9, angle: 6, authority: 5 } },
          },
          {
            source: "tavily",
            title: "Bad scored",
            url: "https://example.com/bad",
            topics: ["ai"],
            score: { mode: "kortform", dimensions: { pillar: 8, audience: 7, timing: 99, angle: 6, authority: 5 } },
          },
        ]);
        const { status, stdout } = run(["capture", "--store", store, "--json"], batch);
        assert.equal(status, 0, "a bad score must not fail the run");
        const summary = JSON.parse(stdout);
        assert.equal(summary.added, 1, "the valid scored item is added");
        assert.equal(summary.errors.length, 1, "the bad-score item lands in errors[]");
        assert.equal(
          summary.added + summary.merged + summary.duplicates + summary.errors.length,
          2,
          "tally must sum to the input size",
        );
      } finally {
        rmSync(join(store, ".."), { recursive: true, force: true });
      }
    });
  });
});

describe("trends CLI — brief subcommand (RE-R2b / Step 3)", () => {
  // brief is flag-driven (reads the store, not stdin). spawn with an env-overridable
  // LINKEDIN_STUDIO_DATA so defaultBriefDir() resolves into a temp root (never the real HOME).
  function runBrief(args: string[], env: Record<string, string> = {}): { status: number | null; stdout: string } {
    const res = spawnSync("node", ["--import", "tsx", "src/cli.ts", "brief", ...args], {
      input: "",
      encoding: "utf8",
      cwd: trendsDir,
      env: { ...process.env, ...env },
    });
    return { status: res.status, stdout: res.stdout };
  }
  const freshIso = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10);
  function seedStore(trends: unknown[]): string {
    const store = join(mkdtempSync(join(tmpdir(), "trends-brief-")), "trends.json");
    writeFileSync(store, JSON.stringify({ schemaVersion: 2, trends }));
    return store;
  }

  test("happy: writes a dated brief, --json carries path/date/totals/summary", () => {
    const store = seedStore([
      { id: "a", title: "Fresh Match", url: "https://e/a", source: "tavily", capturedAt: freshIso, publishedAt: freshIso, topics: ["ai", "gov"] },
    ]);
    const out = mkdtempSync(join(tmpdir(), "brief-out-"));
    try {
      const { status, stdout } = runBrief(["--pillars", "ai,gov", "--store", store, "--out", out, "--json"]);
      assert.equal(status, 0);
      const summary = JSON.parse(stdout);
      assert.match(summary.path, /\d{4}-\d{2}-\d{2}\.md$/);
      assert.match(summary.date, /^\d{4}-\d{2}-\d{2}$/);
      assert.equal(summary.totals.trends, 1);
      assert.equal(summary.totals.fresh, 1);
      assert.ok(existsSync(summary.path), "the dated brief file is written");
      const md = readFileSync(summary.path, "utf8");
      const m = md.match(/^summary: (.*)$/m);
      assert.ok(m, "the brief frontmatter has a summary line");
      assert.equal(m![1], summary.summary, "--json summary equals the file frontmatter summary (one source)");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
      rmSync(out, { recursive: true, force: true });
    }
  });

  test("bad invocation: --fresh-days non-numeric -> exit 2", () => {
    const store = seedStore([]);
    try {
      const { status } = runBrief(["--pillars", "ai", "--store", store, "--fresh-days", "xyz"]);
      assert.equal(status, 2);
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
    }
  });

  test("empty --pillars -> exit 0 + a no-match brief is still written", () => {
    const store = seedStore([
      { id: "a", title: "X", url: "https://e/x", source: "tavily", capturedAt: freshIso, publishedAt: freshIso, topics: ["ai"] },
    ]);
    const out = mkdtempSync(join(tmpdir(), "brief-out-"));
    try {
      const { status, stdout } = runBrief(["--store", store, "--out", out, "--json"]);
      assert.equal(status, 0);
      const summary = JSON.parse(stdout);
      assert.equal(summary.totals.matched, 0, "no pillars -> nothing matched");
      assert.ok(existsSync(summary.path), "a dated no-match brief is still written");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
      rmSync(out, { recursive: true, force: true });
    }
  });

  test("bare --out (no value) -> falls back to defaultBriefDir, never ./true", () => {
    const store = seedStore([]);
    const dataRoot = mkdtempSync(join(tmpdir(), "brief-data-"));
    try {
      // bare --out --json: parseFlags yields out:"true"; the !== "true" guard must
      // fall back to defaultBriefDir() = <LINKEDIN_STUDIO_DATA>/trends/morning-brief.
      const { status, stdout } = runBrief(["--pillars", "ai", "--store", store, "--json", "--out"], { LINKEDIN_STUDIO_DATA: dataRoot });
      assert.equal(status, 0);
      const summary = JSON.parse(stdout);
      assert.ok(
        summary.path.startsWith(join(dataRoot, "trends", "morning-brief")),
        "bare --out must fall back to defaultBriefDir under LINKEDIN_STUDIO_DATA, not ./true",
      );
      assert.ok(!existsSync(join(trendsDir, "true")), "no ./true dir was created");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
      rmSync(dataRoot, { recursive: true, force: true });
    }
  });
});

describe("trends CLI — lifecycle: act/skip/reset + brief surfacing (RE-R3b)", () => {
  // One temp dir per fixture holds both the store file and the brief out dir, so the
  // real per-user data dir (defaultBriefDir) is never touched.
  const fixture = () => {
    const dir = mkdtempSync(join(tmpdir(), "trends-r3b-"));
    return { dir, store: join(dir, "trends.json"), out: join(dir, "briefs") };
  };
  const listJson = (store: string): Array<Record<string, any>> =>
    JSON.parse(run(["list", "--store", store, "--json"], "").stdout);
  const seedScored = (store: string, title: string, url: string, timing = 9): void => {
    const batch = JSON.stringify([
      {
        source: "tavily",
        title,
        url,
        topics: ["ai", "gov"],
        publishedAt: "2026-06-23",
        score: { mode: "kortform", dimensions: { pillar: 9, audience: 8, timing, angle: 7, authority: 6 } },
      },
    ]);
    run(["capture", "--store", store], batch);
  };

  test("RED: act --id → acted; skip → skipped; reset → new (read back via list --json)", () => {
    const { dir, store } = fixture();
    try {
      seedScored(store, "Lifecycle", "https://e/lc");
      const id = listJson(store)[0].id;
      assert.equal(run(["act", "--id", id, "--store", store], "").status, 0);
      assert.equal(listJson(store)[0].status, "acted");
      run(["skip", "--id", id, "--store", store], "");
      assert.equal(listJson(store)[0].status, "skipped");
      run(["reset", "--id", id, "--store", store], "");
      assert.equal(listJson(store)[0].status, "new");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("RED: an unknown id → exit 2 + store unchanged; a missing --id → exit 2", () => {
    const { dir, store } = fixture();
    try {
      seedScored(store, "X", "https://e/x");
      const before = readFileSync(store, "utf8");
      assert.equal(run(["act", "--id", "nope", "--store", store], "").status, 2);
      assert.equal(readFileSync(store, "utf8"), before, "store untouched on a not-found id");
      assert.equal(run(["skip", "--store", store], "").status, 2, "missing --id → exit 2");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("RED: brief records surfacing (surfacedCount + lastSurfacedAt + marked); a second same-day run is idempotent", () => {
    const { dir, store, out } = fixture();
    try {
      seedScored(store, "Surf", "https://e/surf");
      const o1 = JSON.parse(run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store, "--json"], "").stdout);
      assert.equal(o1.marked, 1, "first brief marks 1");
      const rec = listJson(store)[0];
      assert.equal(rec.surfacedCount, 1);
      assert.match(rec.lastSurfacedAt, /^\d{4}-\d{2}-\d{2}$/);
      const o2 = JSON.parse(run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store, "--json"], "").stdout);
      assert.equal(o2.marked, 0, "second same-day brief is idempotent");
      assert.equal(listJson(store)[0].surfacedCount, 1, "count unchanged on the second same-day run");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("RED: brief --no-mark writes no surfacedCount", () => {
    const { dir, store, out } = fixture();
    try {
      seedScored(store, "Dry", "https://e/dry");
      const o = JSON.parse(run(["brief", "--pillars", "ai,gov", "--no-mark", "--out", out, "--store", store, "--json"], "").stdout);
      assert.equal(o.marked, 0);
      assert.equal("surfacedCount" in listJson(store)[0], false, "--no-mark must not write surfacedCount");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("RED: an acted record leaves the work queue and moves to the 'I produksjon' board (N6)", () => {
    const { dir, store, out } = fixture();
    try {
      seedScored(store, "Handled", "https://e/handled");
      const id = listJson(store)[0].id;
      run(["act", "--id", id, "--store", store], "");
      const o = JSON.parse(run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store, "--json"], "").stdout);
      const md = readFileSync(o.path, "utf8");
      // N6: acted no longer vanishes from the whole brief — it leaves the QUEUE and shows in "I produksjon".
      const idx = md.indexOf("## 🚧 I produksjon");
      assert.ok(idx >= 0, "the production section is present");
      assert.ok(!md.slice(0, idx).includes("Handled"), "an acted record must not appear in the work queue");
      assert.ok(md.slice(idx).includes("Handled"), "the acted record appears in I produksjon");
      assert.ok(md.slice(idx).includes("skrevet"), "tagged skrevet (acted)");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("RED: a re-capture with a changed score reports merged:1 + refreshes the composite", () => {
    const { dir, store } = fixture();
    try {
      seedScored(store, "Re", "https://e/re", 9);
      const c1 = listJson(store)[0].score.composite;
      const batch = JSON.stringify([
        {
          source: "tavily",
          title: "Re",
          url: "https://e/re",
          topics: ["ai", "gov"],
          publishedAt: "2026-06-23",
          score: { mode: "kortform", dimensions: { pillar: 9, audience: 8, timing: 2, angle: 7, authority: 6 } },
        },
      ]);
      const o = JSON.parse(run(["capture", "--store", store, "--json"], batch).stdout);
      assert.equal(o.merged, 1, "a changed score on a duplicate → merged");
      const c2 = listJson(store)[0].score.composite;
      assert.ok(c2 < c1, "a lower timing → lower composite (re-score last-wins)");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});

describe("trends CLI — schedule subcommand (RE-R3c / autonomous trigger, print-first)", () => {
  // schedule is flag-driven + print-first. Capture stdout AND stderr (usage → stderr); override HOME
  // (the ~/Library/LaunchAgents target) + LINKEDIN_STUDIO_DATA (the cron.log seam) into a temp dir so
  // a real HOME is never touched. (os.homedir() respects $HOME on POSIX — verified.)
  function runSched(
    args: string[],
    env: Record<string, string> = {},
  ): { status: number | null; stdout: string; stderr: string } {
    const res = spawnSync("node", ["--import", "tsx", "src/cli.ts", "schedule", ...args], {
      input: "",
      encoding: "utf8",
      cwd: trendsDir,
      env: { ...process.env, ...env },
    });
    return { status: res.status, stdout: res.stdout, stderr: res.stderr };
  }
  const tmpHome = () => mkdtempSync(join(tmpdir(), "sched-home-"));

  // A dependency-free well-formedness check: tokenize element tags and assert they nest/balance
  // (the `<?xml?>` PI and `<!DOCTYPE>` are skipped — neither starts with a letter after `<`).
  // SC1 asserts balance + key-completeness; `plutil -lint` is the deps-present manual check (Step 7).
  function isBalancedXml(xml: string): boolean {
    const stack: string[] = [];
    const re = /<(\/?)([a-zA-Z][\w.:-]*)[^>]*?(\/?)>/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(xml)) !== null) {
      if (m[3] === "/") continue; // self-closing (e.g. <false/>)
      if (m[1] === "/") {
        if (stack.pop() !== m[2]) return false;
      } else {
        stack.push(m[2]);
      }
    }
    return stack.length === 0;
  }

  test("SC1: --platform launchd --at 07:30 --print → key-complete, well-formed plist, exit 0", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(
        ["--pillars", "ai,gov", "--platform", "launchd", "--at", "07:30", "--print"],
        { HOME: home, LINKEDIN_STUDIO_DATA: home },
      );
      assert.equal(status, 0);
      assert.match(stdout, /<key>Label<\/key>\s*<string>com\.linkedin-studio\.trends\.daily<\/string>/);
      assert.ok(stdout.includes("<key>ProgramArguments</key>"), "ProgramArguments present");
      assert.ok(stdout.includes("run-daily.sh"), "invokes the wrapper");
      assert.ok(stdout.includes("--pillars") && stdout.includes("ai,gov"), "carries the pillars");
      assert.match(stdout, /<key>Hour<\/key>\s*<integer>7<\/integer>/, "Hour 7");
      assert.match(stdout, /<key>Minute<\/key>\s*<integer>30<\/integer>/, "Minute 30");
      assert.ok(stdout.includes("<key>StandardOutPath</key>") && stdout.includes("<key>StandardErrorPath</key>"), "Std*Path present");
      assert.ok(stdout.includes("cron.log"), "Std*Path point at cron.log");
      assert.ok(stdout.includes("<key>EnvironmentVariables</key>"), "EnvironmentVariables present");
      assert.ok(stdout.includes("NODE_BIN") && stdout.includes("LINKEDIN_STUDIO_DATA"), "env carries NODE_BIN + data root");
      assert.ok(isBalancedXml(stdout), "the plist XML is balanced / well-formed");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC1: two --print runs (same args) are byte-identical (the emitter is pure)", () => {
    const home = tmpHome();
    try {
      const a = runSched(["--pillars", "ai,gov", "--platform", "launchd", "--print"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      const b = runSched(["--pillars", "ai,gov", "--platform", "launchd", "--print"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      assert.equal(a.status, 0);
      assert.equal(a.stdout, b.stdout);
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC2: --platform cron --at 07:30 --print → cron line + install recipe (string only), exit 0", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(
        ["--pillars", "ai,gov", "--platform", "cron", "--at", "07:30", "--print"],
        { HOME: home, LINKEDIN_STUDIO_DATA: home },
      );
      assert.equal(status, 0);
      assert.match(stdout, /^30 7 \* \* \* /m, "the cron line fires at 07:30 daily");
      assert.ok(stdout.includes("run-daily.sh"), "invokes the wrapper");
      assert.ok(stdout.includes("--pillars ai,gov"), "carries the pillars");
      assert.ok(stdout.includes(">> ") && stdout.includes("2>&1"), "redirects stdout+stderr to the log");
      assert.ok(stdout.includes("com.linkedin-studio.trends.daily"), "the label comment");
      assert.ok(stdout.includes("crontab -"), "the install recipe is printed (a string the operator runs)");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC3: platform auto (no --platform) → launchd on darwin, cron elsewhere", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(["--pillars", "ai", "--print"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      assert.equal(status, 0);
      if (process.platform === "darwin") {
        assert.ok(stdout.includes("<key>Label</key>"), "darwin auto → launchd plist");
      } else {
        assert.match(stdout, /^\d+ \d+ \* \* \* /m, "non-darwin auto → cron line");
      }
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC4: --print writes nothing (temp-HOME LaunchAgents stays absent), exit 0", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(["--pillars", "ai", "--platform", "launchd", "--print"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      assert.equal(status, 0);
      assert.ok(stdout.includes("<key>Label</key>"), "the plist is on stdout");
      assert.ok(!existsSync(join(home, "Library", "LaunchAgents")), "--print creates no LaunchAgents dir");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC5: --install launchd → inert plist FILE written + launchctl printed (never run), exit 0", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(["--pillars", "ai", "--platform", "launchd", "--install"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      assert.equal(status, 0);
      const plist = join(home, "Library", "LaunchAgents", "com.linkedin-studio.trends.daily.plist");
      assert.ok(existsSync(plist), "the inert plist file is written");
      const content = readFileSync(plist, "utf8");
      assert.ok(content.includes("<key>Label</key>") && content.includes("com.linkedin-studio.trends.daily"), "the file holds the plist");
      assert.ok(stdout.includes("launchctl bootstrap"), "the activation command is PRINTED (the tool never runs launchctl)");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC6: --install cron → line + install recipe printed, writes no file, exit 0", () => {
    const home = tmpHome();
    try {
      const { status, stdout } = runSched(["--pillars", "ai", "--platform", "cron", "--install"], { HOME: home, LINKEDIN_STUDIO_DATA: home });
      assert.equal(status, 0);
      assert.match(stdout, /^\d+ \d+ \* \* \* /m, "the cron line is printed");
      assert.ok(stdout.includes("crontab -"), "the install recipe is printed (never executed)");
      assert.ok(!existsSync(join(home, "Library", "LaunchAgents")), "cron --install writes no plist");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  test("SC9: no --pillars / bad --at / bad --platform → exit 2; the fs is untouched", () => {
    const home = tmpHome();
    try {
      assert.equal(runSched([], { HOME: home, LINKEDIN_STUDIO_DATA: home }).status, 2, "no --pillars → exit 2");
      assert.equal(runSched(["--pillars", "ai", "--at", "25:00"], { HOME: home, LINKEDIN_STUDIO_DATA: home }).status, 2, "--at 25:00 → exit 2");
      assert.equal(runSched(["--pillars", "ai", "--at", "7:99"], { HOME: home, LINKEDIN_STUDIO_DATA: home }).status, 2, "--at 7:99 → exit 2");
      assert.equal(runSched(["--pillars", "ai", "--at", "noon"], { HOME: home, LINKEDIN_STUDIO_DATA: home }).status, 2, "--at noon → exit 2");
      assert.equal(runSched(["--pillars", "ai", "--platform", "bogus"], { HOME: home, LINKEDIN_STUDIO_DATA: home }).status, 2, "--platform bogus → exit 2");
      assert.ok(!existsSync(join(home, "Library", "LaunchAgents")), "a validation error writes nothing");
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });
});

describe("trends CLI — brief temporal flags (RE-R3d / SC6)", () => {
  // brief is flag-driven; spawn into a temp store/out so the real per-user data dir is never touched.
  function runBrief(args: string[], env: Record<string, string> = {}): { status: number | null; stdout: string } {
    const res = spawnSync("node", ["--import", "tsx", "src/cli.ts", "brief", ...args], {
      input: "",
      encoding: "utf8",
      cwd: trendsDir,
      env: { ...process.env, ...env },
    });
    return { status: res.status, stdout: res.stdout };
  }
  const freshIso = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10);
  function seedStore(trends: unknown[]): string {
    const store = join(mkdtempSync(join(tmpdir(), "trends-r3d-")), "trends.json");
    writeFileSync(store, JSON.stringify({ schemaVersion: 2, trends }));
    return store;
  }
  // --no-mark so sequential runs on the same store do NOT accumulate surfacedCount (which would
  // confound the threshold assertions); tier badges live in the .md body, not in --json.
  function briefMd(args: string[]): { status: number | null; md: string } {
    const out = mkdtempSync(join(tmpdir(), "r3d-out-"));
    const { status, stdout } = runBrief([...args, "--out", out, "--no-mark", "--json"]);
    const path = status === 0 ? (JSON.parse(stdout).path as string) : "";
    return { status, md: path ? readFileSync(path, "utf8") : "" };
  }

  test("--saturation-at 2 escalates a surfacedCount-2 trend from warming (sett 2x) to saturated (mettet 2x)", () => {
    const store = seedStore([
      { id: "s", title: "Seen", url: "https://e/s", source: "tavily", capturedAt: freshIso, publishedAt: freshIso, topics: ["ai"], surfacedCount: 2 },
    ]);
    try {
      const dflt = briefMd(["--pillars", "ai", "--store", store]);
      assert.equal(dflt.status, 0);
      assert.ok(dflt.md.includes("· sett 2x"), "default saturationAt 3 -> surfacedCount 2 is warming");
      const tuned = briefMd(["--pillars", "ai", "--store", store, "--saturation-at", "2"]);
      assert.equal(tuned.status, 0);
      assert.ok(tuned.md.includes("· 🔁 mettet (2x)"), "--saturation-at 2 -> surfacedCount 2 is saturated");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
    }
  });

  test("--first-mover-days 1 drops a 2-day-old unsurfaced trend out of first-mover", () => {
    const store = seedStore([
      { id: "f", title: "Fresh", url: "https://e/f", source: "tavily", capturedAt: freshIso, publishedAt: freshIso, topics: ["ai"] },
    ]);
    try {
      const dflt = briefMd(["--pillars", "ai", "--store", store]);
      assert.ok(dflt.md.includes("· 🥇 først ute"), "default firstMoverDays 2 -> a 2-day unsurfaced trend is first-mover");
      const tuned = briefMd(["--pillars", "ai", "--store", store, "--first-mover-days", "1"]);
      assert.ok(!tuned.md.includes("først ute"), "--first-mover-days 1 -> a 2-day trend is neutral");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
    }
  });

  test("invalid threshold flags -> exit 2", () => {
    const store = seedStore([]);
    try {
      assert.equal(runBrief(["--pillars", "ai", "--store", store, "--first-mover-days", "x"]).status, 2, "--first-mover-days x");
      assert.equal(runBrief(["--pillars", "ai", "--store", store, "--first-mover-days", "-1"]).status, 2, "--first-mover-days -1");
      assert.equal(runBrief(["--pillars", "ai", "--store", store, "--saturation-at", "0"]).status, 2, "--saturation-at 0");
      assert.equal(runBrief(["--pillars", "ai", "--store", store, "--saturation-at", "x"]).status, 2, "--saturation-at x");
    } finally {
      rmSync(join(store, ".."), { recursive: true, force: true });
    }
  });
});

describe("trends CLI — brief history + day-over-day diff (RE-R3e / SC9)", () => {
  const fixture = () => {
    const dir = mkdtempSync(join(tmpdir(), "trends-r3e-"));
    return { dir, store: join(dir, "trends.json"), out: join(dir, "briefs") };
  };
  // freshIso keeps the seeds inside the freshness window regardless of when the test runs.
  const fresh = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10);
  const seedOnPillar = (store: string, title: string, url: string): void => {
    const batch = JSON.stringify([
      {
        source: "tavily",
        title,
        url,
        topics: ["ai", "gov"],
        publishedAt: fresh,
        score: { mode: "kortform", dimensions: { pillar: 9, audience: 8, timing: 9, angle: 7, authority: 6 } },
      },
    ]);
    run(["capture", "--store", store], batch);
  };
  const briefJson = (store: string, out: string) =>
    JSON.parse(run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store, "--json"], "").stdout);

  test("two-day (rename-real-write): day-2 shows the new trend; --json carries the diff", () => {
    const { dir, store, out } = fixture();
    try {
      // Day 1 — two on-pillar trends. The brief records its surfaced cohort + a null-prior diff.
      seedOnPillar(store, "Alpha", "https://e/a");
      seedOnPillar(store, "Beta", "https://e/b");
      const o1 = briefJson(store, out);
      assert.equal(o1.diff.priorDate, null, "first brief has no prior (empty dir)");
      assert.match(readFileSync(o1.path, "utf8"), /^surfaced: .+/m, "day-1 records a non-empty surfaced: line");

      // Rename the REAL day-1 brief to a fixed past date — its surfaced: ids are genuine store
      // ids, so the day-2 diff's carried/added are id-exact, clock-free (no today() advance).
      const prior = "2026-06-20";
      renameSync(o1.path, join(out, `${prior}.md`));

      // Day 2 — capture one NEW on-pillar trend, re-run. It is the sole "added".
      seedOnPillar(store, "Gamma", "https://e/g");
      const o2 = briefJson(store, out);
      assert.equal(o2.diff.priorDate, prior, "day-2 discovers the renamed strict-prior");
      assert.ok(o2.diff.added >= 1, "at least the new trend is added");
      assert.equal(o2.diff.carried, 2, "the two day-1 trends carry over");
      assert.equal(o2.diff.dropped, 0, "nothing dropped");
      const md2 = readFileSync(o2.path, "utf8");
      assert.ok(md2.includes(`## 🆕 Nytt siden sist (${prior})`), "the diff section names the prior date");
      assert.ok(md2.includes("Gamma"), "the new trend's title is in the Nytt-siden-sist section");

      // The non-JSON console line appends the delta marker.
      const console2 = run(["brief", "--pillars", "ai,gov", "--out", out, "--store", store], "").stdout;
      assert.ok(console2.includes("nye siden sist"), `console line carries the delta: ${console2}`);
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });

  test("a first run (empty dir) → diff.priorDate === null, no Nytt-siden-sist date", () => {
    const { dir, store, out } = fixture();
    try {
      seedOnPillar(store, "Solo", "https://e/s");
      const o = briefJson(store, out);
      assert.equal(o.diff.priorDate, null);
      const md = readFileSync(o.path, "utf8");
      assert.ok(md.includes("Første brief"), "a first brief says 'Første brief'");
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  });
});
