import { runHwlabCli } from "../tools/src/hwlab-cli-lib.ts";

const streamingText = "streaming ".repeat(2000);

const result = await runHwlabCli(["client", "agent", "trace", "trc_stream_722", "--base-url", "http://web.test", "--cookie", "hwlab_session=session-a", "--render", "web", "--full"], {
  fetchImpl: async () => new Response(JSON.stringify({
    status: "completed",
    traceId: "trc_stream_722",
    events: [
      { traceId: "trc_stream_722", seq: 1, label: "request:accepted", status: "accepted", createdAt: "2026-06-02T15:00:00.000Z", promptSummary: "请继续" },
      { traceId: "trc_stream_722", seq: 2, label: "assistant:item_completed", type: "assistant_message", status: "completed", itemId: "msg_streaming", createdAt: "2026-06-02T15:00:01.000Z", message: streamingText },
      { traceId: "trc_stream_722", seq: 3, label: "assistant:completed", type: "assistant_message", terminal: true, status: "completed", itemId: "assistant-final", createdAt: "2026-06-02T15:00:02.000Z", message: "完成" }
    ],
    assistantStreams: [{ itemId: "msg_streaming", text: streamingText, chunkCount: 1 }, { itemId: "assistant-final", text: "完成", chunkCount: 1 }]
  }), { status: 200 })
});

const body = result.payload.body;
const streamingRow = (body.rows ?? []).find((r) => r.rowId === "event:2");
const terminalRow = (body.rows ?? []).find((r) => r.terminal === true);
console.log("CLI exitCode:", result.exitCode);
console.log("CLI streaming row terminal flag:", streamingRow?.terminal);
console.log("CLI streaming row body length:", streamingRow?.body?.length);
console.log("CLI streaming row has ... marker:", streamingRow?.body?.endsWith("..."));
console.log("CLI terminal row body length:", terminalRow?.body?.length);
console.log("CLI terminal row body === final response text:", terminalRow?.body === "完成");

const streamingOk = streamingRow?.body && streamingRow.body.endsWith("...") && streamingRow.body.length <= 1203;
const terminalOk = terminalRow?.body === "完成";
if (streamingOk && terminalOk) {
  console.log(`\nPASS: streaming row CLI preview capped at ${streamingRow.body.length} chars; terminal row keeps full text`);
  process.exit(0);
} else {
  console.log(`\nFAIL: streamingOk=${streamingOk} terminalOk=${terminalOk}`);
  process.exit(1);
}
