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

import { collectAgentObserverRuns } from "../src/hwlab-cli/agent-observer-client.ts";

test("agent observer CLI collects unscoped Artificer runs through retention-to-live SSE", async () => {
  const envelope = {
    schema: "hwlab.event.v1",
    runId: "run_artificer_test",
    sessionId: "sess_artificer_test",
    producedAt: "2026-07-16T02:24:51.000Z",
    context: { projectId: "pikainc/pikaoa", runId: "run_artificer_test" },
    event: { runId: "run_artificer_test", lane: "release", backend: "gpt-pika", runStatus: "running", createdAt: "2026-07-16T02:24:50.000Z" }
  };
  const frames = [
    `event: hwlab.event.v1\ndata: ${JSON.stringify(envelope)}\n\n`,
    `event: agent-observer.handoff\ndata: ${JSON.stringify({ replay: { scannedCount: 12, deliveredCount: 1 } })}\n\n`,
    `event: agent-observer.connected\ndata: ${JSON.stringify({ replay: { scannedCount: 12, deliveredCount: 1 } })}\n\n`
  ].join("");
  let authorization = "";
  const result = await collectAgentObserverRuns({
    fetchImpl: async (_url, init) => {
      authorization = new Headers(init?.headers).get("authorization") ?? "";
      return new Response(frames, { status: 200, headers: { "content-type": "text/event-stream" } });
    },
    url: "https://lab-dev.hwpod.com/v1/agent-observer/events",
    apiKey: "hwl_live_test_only",
    timeoutMs: 1000,
    limit: 20
  });

  assert.equal(authorization, "Bearer hwl_live_test_only");
  assert.equal(result.phase, "live");
  assert.equal(result.eventCount, 1);
  assert.equal(result.runCount, 1);
  assert.equal(result.runs[0].runId, "run_artificer_test");
  assert.equal(result.runs[0].lane, "release");
  assert.equal(result.runs[0].backend, "gpt-pika");
});
