import { describe, expect, test } from "bun:test";
import { readToolSuggestSource } from "./toolSuggest";

describe("readToolSuggestSource", () => {
  test("maps each JSONL record to an event carrying verdict, rule and command", () => {
    const fixture = [
      JSON.stringify({ ts: 1762483200, verdict: "suggest", ruleId: "worktree-add-raw-suggest", command: "git worktree add .worktrees/x x", source: "hook" }),
      JSON.stringify({ ts: 1762483260, verdict: "deny", ruleId: "worktree-outside-repo", command: "git worktree add ~/scratch x", source: "hook" }),
    ].join("\n");

    const { coverage, events } = readToolSuggestSource({
      path: "/tmp/suggest-log.jsonl",
      existsSyncImpl: () => true,
      readFileImpl: () => fixture,
    });

    expect(coverage).toEqual({
      id: "tool-suggest",
      label: "tool wrapper suggestions",
      category: "guard",
      path: "/tmp/suggest-log.jsonl",
      status: "ok",
      records: 2,
      totalRecords: 2,
      skipped: 0,
      earliest: new Date(1762483200 * 1000).toISOString(),
      latest: new Date(1762483260 * 1000).toISOString(),
    });

    expect(events).toHaveLength(2);
    expect(events[0]).toMatchObject({
      id: "tool-suggest:1",
      category: "guard",
      source: "tool-suggest",
      actor: "agent",
      severity: "info",
      title: "suggest (worktree-add-raw-suggest) via hook: git worktree add .worktrees/x x",
      dedupeKey: "suggest:worktree-add-raw-suggest:git worktree add .worktrees/x x",
    });
    expect(events[1]).toMatchObject({ severity: "notice" });
    expect(events[1]?.detail).toMatchObject({ verdict: "deny", ruleId: "worktree-outside-repo", source: "hook" });
  });

  test("reports absent when the log has never been written", () => {
    const { coverage, events } = readToolSuggestSource({
      path: "/nowhere/suggest-log.jsonl",
      existsSyncImpl: () => false,
    });
    expect(coverage.status).toBe("absent");
    expect(events).toEqual([]);
  });

  test("skips corrupt lines without losing the sound ones", () => {
    const { coverage, events } = readToolSuggestSource({
      path: "/tmp/suggest-log.jsonl",
      existsSyncImpl: () => true,
      readFileImpl: () => [
        "{ not json",
        JSON.stringify({ verdict: "suggest", command: "x" }),
        JSON.stringify({ ts: 1762483200, verdict: "suggest", command: "git worktree add .worktrees/x x", source: "shim" }),
      ].join("\n"),
    });
    expect(coverage.skipped).toBe(2);
    expect(events).toHaveLength(1);
    expect(events[0]?.title).toContain("git worktree add .worktrees/x x");
  });
});
