import assert from "node:assert/strict";
import { test } from "bun:test";

import type { AgentChatResultResponse, ChatMessage } from "../types";
import { terminalSealResultWithoutTraceEvents, traceDetailProjectedSeq, traceNextProjectedSeq } from "./workbench-trace-detail";

test("trace detail read cursor prefers range metadata over scanning events", () => {
  const trace: ChatMessage["runnerTrace"] = {
    traceId: "trc_cursor_metadata",
    nextProjectedSeq: 42,
    range: { toProjectedSeq: 42 },
    events: [{ projectedSeq: 1, type: "event" }]
  };

  assert.equal(traceDetailProjectedSeq(trace), 42);
});

test("trace result next cursor uses metadata before event fallback", () => {
  const result: AgentChatResultResponse = {
    traceId: "trc_result_cursor",
    status: "running",
    range: { toProjectedSeq: 12 },
    events: [{ projectedSeq: 3, type: "event" }]
  };

  assert.equal(traceNextProjectedSeq(result, 8), 12);
});

test("terminal seal strips heavy trace rows while preserving final authority", () => {
  const result: AgentChatResultResponse = {
    traceId: "trc_terminal_seal",
    status: "completed",
    terminal: true,
    finalResponse: { text: "final answer" },
    events: [{ projectedSeq: 1, type: "event" }],
    traceEvents: [{ projectedSeq: 2, type: "event" }],
    runnerTrace: {
      traceId: "trc_terminal_seal",
      status: "completed",
      traceStatus: "completed",
      events: [{ projectedSeq: 3, type: "event" }]
    }
  };

  const sealed = terminalSealResultWithoutTraceEvents(result);

  assert.equal(sealed.status, "completed");
  assert.equal((sealed.finalResponse as { text?: string } | null | undefined)?.text, "final answer");
  assert.equal(sealed.events, undefined);
  assert.equal(sealed.traceEvents, undefined);
  assert.equal(sealed.runnerTrace?.events, undefined);
  assert.equal(sealed.runnerTrace?.traceStatus, "completed");
});
