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

import { createCodeAgentTraceStore } from "./code-agent-trace-store.ts";

test("code agent trace store keeps assistant deltas outside event count", () => {
  const traceStore = createCodeAgentTraceStore({ maxEvents: 6000 });
  const traceId = "trc_trace-store-assistant-stream";
  traceStore.append(traceId, { type: "request", status: "accepted", label: "request:accepted" });
  for (let index = 0; index < 6200; index += 1) {
    traceStore.appendAssistantDelta(traceId, {
      itemId: "item_assistant_stream",
      chunk: `chunk-${index} `,
      waitingFor: "turn/completed"
    });
  }
  const snapshot = traceStore.snapshot(traceId);
  assert.equal(snapshot.eventCount, 1);
  assert.equal(snapshot.events.length, 1);
  assert.equal(snapshot.events[0].label, "request:accepted");
  assert.equal(snapshot.assistantStreams.length, 1);
  assert.equal(snapshot.assistantStreams[0].chunkCount, 6200);
  assert.equal(snapshot.waitingFor, "turn/completed");
});

test("code agent trace store retains six thousand regular events", () => {
  const traceStore = createCodeAgentTraceStore({ maxEvents: 6000 });
  const traceId = "trc_trace-store-regular-events";
  for (let index = 0; index < 6001; index += 1) {
    traceStore.append(traceId, { type: "trace", status: "observed", label: `event:${index}` });
  }
  const snapshot = traceStore.snapshot(traceId);
  assert.equal(snapshot.eventCount, 6000);
  assert.equal(snapshot.events.length, 6000);
  assert.equal(snapshot.events[0].label, "event:1");
  assert.equal(snapshot.events.at(-1).label, "event:6000");
});

test("code agent trace store preserves upstream event timestamps", () => {
  const traceStore = createCodeAgentTraceStore({ maxEvents: 10 });
  const traceId = "trc_trace-store-upstream-time";
  traceStore.append(traceId, {
    type: "backend",
    status: "running",
    label: "agentrun:backend:turn/completed",
    createdAt: "2026-06-01T16:35:40.939Z"
  }, { now: "2026-06-01T16:35:56.171Z" });
  const snapshot = traceStore.snapshot(traceId);
  assert.equal(snapshot.events[0].createdAt, "2026-06-01T16:35:40.939Z");
  assert.equal(snapshot.elapsedMs, 0);
});
