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

const longFinalResponse = `下面是北京时间 2026-06-02 的开发进展总结。三个仓库共 67 个 PR：HWLAB 39 个（全部已合）、AgentRun 27 个已合 + 1 个 OPEN、unidesk 今天没有 PR。功能开发：HWLAB v0.2 Code Agent 接入 AgentRun v0.1 调度。` + "x".repeat(4000) + " 完。";

const result = await runHwlabCli(["client", "agent", "trace", "trc_issue_722", "--base-url", "http://web.test", "--cookie", "hwlab_session=session-a", "--render", "web", "--full"], {
  fetchImpl: async () => new Response(JSON.stringify({
    status: "completed",
    traceId: "trc_issue_722",
    events: [
      { traceId: "trc_issue_722", seq: 1, label: "request:accepted", status: "accepted", createdAt: "2026-06-02T15:09:01.000Z", promptSummary: "总结" },
      { traceId: "trc_issue_722", seq: 6, label: "assistant:completed", type: "assistant_message", terminal: true, status: "completed", itemId: "assistant-final", createdAt: "2026-06-02T15:15:40.000Z", message: longFinalResponse }
    ],
    assistantStreams: [{ itemId: "assistant-final", text: longFinalResponse, chunkCount: 12 }]
  }), { status: 200 })
});

const body = result.payload.body;
const terminalRow = (body.rows ?? []).find((r) => r.terminal === true);
console.log("CLI exitCode:", result.exitCode);
console.log("CLI render:", body?.render);
console.log("CLI body.assistantText length:", body?.assistantText?.length);
console.log("CLI terminal row body length:", terminalRow?.body?.length);
console.log("CLI terminal row body === full text:", terminalRow?.body === longFinalResponse);
console.log("CLI terminal row body has trunc marker:", terminalRow?.body?.includes("内容已截断"));
const expected = longFinalResponse.length;
const actual = terminalRow?.body?.length ?? 0;
if (actual === expected && !terminalRow.body.includes("内容已截断")) {
  console.log(`\nPASS: terminal final-response body keeps full ${expected} chars (CLI integration)`);
  process.exit(0);
} else {
  console.log(`\nFAIL: terminal body length ${actual} != expected ${expected}`);
  process.exit(1);
}
