import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Chunked reads count two files and keep three tool rows", WEB, async ({ t3, app, screen }) => {
  const a = Array.from({length:120}, (_, i) => `export const line${i+1} = ${i+1};`).join("\n");
  const project = await t3.project("proj", { "src/a.ts": a, "src/b.ts": "export const b = 1;\n" });
  const transcript = Path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await FS.readFile(transcript, "utf8");
  const frames: unknown[] = [{type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}}];
  const update = (value: unknown) => frames.push({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:value}}});
  for (const [i, file, offset, limit] of [[1,"a.ts",1,50],[2,"a.ts",50,50],[3,"b.ts",1,50]] as const) {
    update({sessionUpdate:"tool_call",toolCallId:`read-${i}`,kind:"read",title:"Read",status:"in_progress",rawInput:{file_path:`<workspace>/src/${file}`,offset,limit}});
    const lines = file === "a.ts" ? a.split("\n").slice(offset-1,offset-1+limit).map((line,j)=>`${offset+j}  ${line}`).join("\n") : "1  export const b = 1;";
    update({sessionUpdate:"tool_call_update",toolCallId:`read-${i}`,status:"completed",rawOutput:lines,content:[{type:"content",content:{type:"text",text:lines}}]});
  }
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"done"}});
  frames.push({type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}});
  try {
    await FS.writeFile(transcript, frames.map(x=>JSON.stringify(x)).join("\n")+"\n");
    const thread = await t3.thread({project,title:"Read files in chunks",messages:["Read src/a.ts offset 1 limit 50, then src/a.ts offset 50 limit 50, then src/b.ts, and reply done."],model:"command-output"});
    await t3.open(thread);
    await screen.getByText("done",{exact:true}).waitFor();
    await screen.getByRole("button","Worked for",{exact:false}).tap();
    await app.screenshot("collapsed-read-summary");
    await screen.getByRole("button",/^Read [23] files$/).tap();
    await app.screenshot("expanded-three-read-rows");
    await expect(screen.getByRole("button", "Read 2 files", {exact:true})).toBeVisible();
    await expect(screen.getByRole("button", /^Read proj\/src\/a\.ts/)).toHaveCount(2);
    await expect(screen.getByRole("button", /^Read proj\/src\/b\.ts/)).toHaveCount(1);
  } finally { await FS.writeFile(transcript, original); }
});
