import assert from "node:assert/strict";
import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";

import { taskMarkdown } from "../../lifecycle/__tests__/helpers.ts";
import { LedgerBuilder } from "../LedgerBuilder.ts";
import { resolveLedgerLayout } from "../paths.ts";
import { verifyThread } from "../LedgerVerifier.ts";

describe("LedgerVerifier read-only mode", () => {
  it("does not rebuild ledger views during stall diagnostics", async () => {
    const root = await mkdtemp(join(tmpdir(), "ledger-verify-readonly-"));
    try {
      const layout = resolveLedgerLayout(root);
      const activeDir = join(layout.lifecycleRoot, "active");
      await mkdir(activeDir, { recursive: true });
      const taskId = "TASK-20260810-001-ADMIN-to-PM";
      await writeFile(
        join(activeDir, `${taskId}.md`),
        taskMarkdown({
          protocol: "fcop",
          version: 1,
          kind: "task",
          task_id: taskId,
          sender: "ADMIN",
          recipient: "PM",
          thread_key: "ledger-read-only",
        }, "# Main\n"),
        "utf-8",
      );
      await new LedgerBuilder({ projectRoot: root }).rebuild();
      const viewsDir = join(layout.ledgerDir, "views");
      await rm(viewsDir, { recursive: true, force: true });

      const result = await verifyThread(root, taskId, { refreshLedger: false });

      assert.equal(result.rebuild.viewsWritten, 0);
      assert.equal(result.list_tasks_all, 1);
      await assert.rejects(access(viewsDir));
    } finally {
      await rm(root, { recursive: true, force: true });
    }
  });
});
