/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Tool-call diff names an absolute edit relative to the workspace", WEB, async ({t3, app, browser, screen}) => {
  const repo = await t3.project("repo", {"apps/web/src/a.ts": "export const a = 1;\n"});
  const root = `/tmp/factory-pr-32697-a1794721546-evidence-2/run-${Date.now()}/repo`;
  await fs.mkdir(root.substring(0, root.lastIndexOf("/")), {recursive:true});
  await fs.cp(repo, root, {recursive:true});
  const project = `${root}/apps/web`;
  const {cli} = makeState(T3_HOME);
  await runPromise(cli(["project", "add", project, "--title", "Tool diff proof"]));
  const recording = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await fs.readFile(recording, "utf8");
  const path = "<workspace>/src/a.ts";
  const update = (value: unknown) => ({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:value}}});
  const transcript = [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    update({sessionUpdate:"tool_call",toolCallId:"read",kind:"read",title:"Read",status:"completed",rawInput:{file_path:path},content:[{type:"content",content:{type:"text",text:"export const a = 1;\n"}}]}),
    update({sessionUpdate:"tool_call",toolCallId:"edit",kind:"edit",title:"Edit",status:"completed",rawInput:{file_path:path,old_string:"export const a = 1;",new_string:"export const a = 2;"},content:[{type:"diff",path,oldText:"export const a = 1;\n",newText:"export const a = 2;\n"}]}),
    update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Changed a from 1 to 2."}}),
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
  ].map(v=>JSON.stringify(v)).join("\n");
  try {
    await fs.writeFile(recording, transcript);
    await fs.writeFile(`${project}/src/a.ts`, "export const a = 2;\n");
    const thread = await t3.thread({project,title:"Absolute-path edit",messages:["Use Edit with the absolute filename to change a = 1 to a = 2."],model:"showcase"});
    await t3.open(thread);
    await screen.getByText("Changed a from 1 to 2.", {exact:true}).waitFor({timeout:60000});
    await screen.getByRole("button", "Worked for", {exact:false}).tap();
    await screen.getByRole("button", "Read 1 file and changed 1 file").tap();
    await screen.getByRole("button", "web/src/a.ts", {exact:true}).tap();
    await screen.getByRole("button", "Open diff", {exact:true}).tap();
    await screen.getByText("Tool call", {exact:true}).waitFor();
    await screen.getByRole("button", /^Expand .*src\/a\.ts$/).tap();
    const headers = () => browser.evaluate(() => Array.from(document.querySelectorAll("*")).flatMap(host => Array.from(host.shadowRoot?.querySelectorAll("[data-diffs-header] [data-title]") ?? [], n => n.textContent ?? "")));
    await expect.poll(headers).not.toEqual([]);
    await app.screenshot("tool-call-diff-header");
    await expect.poll(headers).toEqual(["src/a.ts"]);
    await browser.evaluate(() => { for (const host of document.querySelectorAll("*")) {const h=host.shadowRoot?.querySelector<HTMLElement>("[data-diffs-header] [data-title]"); if(h){h.click();return;}}});
    await screen.getByText("export const a = 2;", {exact:false}).waitFor();
    await app.screenshot("opened-file");
  } finally { await fs.writeFile(recording, original); }
});
