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

test("Browser automation uploads the exact trailing-space filename", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Upload proof", { "report.txt": "wrong neighbor", "report.txt ": "intended" });
  const thread = await t3.thread({ project, title: "Literal filename upload", messages: ["Ready"], model: "default" });
  await t3.open(thread);
  // Use only the Replay process belonging to this scenario's thread.
  let authorization = "";
  let endpoint = "";
  let replayPid = 0;
  for (const pid of await fs.readdir("/proc")) {
    if (!/^\d+$/.test(pid)) continue;
    const raw = await fs.readFile(`/proc/${pid}/environ`, "utf8").catch(() => "");
    const env = Object.fromEntries(raw.split("\0").map(pair => { const i = pair.indexOf("="); return [pair.slice(0,i), pair.slice(i+1)]; }));
    if (env.T3CODE_THREAD_ID !== thread.threadId) continue;
    authorization = env.T3_ACP_MCP_AUTHORIZATION ?? "";
    endpoint = env.T3_ACP_MCP_ENDPOINT ?? "";
    if (authorization && endpoint) { replayPid = Number(pid); break; }
  }
  if (!authorization) throw new Error("Replay thread MCP credential not available in process environment");
  await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Hold the upload proof", "--json"]));
  process.kill(replayPid, "SIGSTOP");
  let session = ""; let id = 0;
  async function send(method: string, params?: unknown) {
    const response = await fetch(endpoint, { method: "POST", headers: { authorization, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? {"mcp-session-id": session} : {}) }, body: JSON.stringify({jsonrpc:"2.0", ...(method.startsWith("notifications/") ? {} : {id: ++id}), method, params}) });
    session = response.headers.get("mcp-session-id") ?? session;
    const text = await response.text();
    if (!response.ok) throw new Error(`MCP HTTP ${response.status}: ${text}`);
    if (!text) return null;
    const data = text.startsWith("event:") || text.startsWith("data:") ? text.split("\n").filter(s => s.startsWith("data: ")).map(s => JSON.parse(s.slice(6))).find(x => x.id === id) : JSON.parse(text);
    if (data?.error || data?.result?.isError) throw new Error(JSON.stringify(data));
    return data?.result;
  }
  const tool = (name: string, args: unknown) => send("tools/call", {name, arguments: args});
  const server = http.createServer((_req,res) => { res.writeHead(200,{"content-type":"text/html"}); res.end(`<!doctype html><title>Exact upload proof</title><style>body{font:22px system-ui;padding:36px;background:#fff;color:#172033}pre{white-space:pre-wrap;font-size:24px;padding:20px;background:#eef2f6}</style><h1>Literal filename upload</h1><p>Requested filename: <b>"report.txt "</b> (one trailing space)</p><p>Expected contents: <b>intended</b></p><input type=file><pre id=result>Waiting for upload</pre><script>document.querySelector('input').onchange=async e=>{const f=e.target.files[0];document.querySelector('#result').textContent=JSON.stringify({name:f.name,text:await f.text()},null,2)}</script>`); });
  await new Promise<void>(r => server.listen(0,"127.0.0.1",r));
  try {
    await send("initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"upload-proof",version:"1"}});
    await send("notifications/initialized");
    const address = server.address() as {port:number};
    await tool("preview_open",{url:`http://127.0.0.1:${address.port}`,open:true});
    await screen.getByRole("button", "Open preview in right panel").waitFor({timeout:15000});
    await browser.evaluate(() => { document.querySelector<HTMLButtonElement>('[aria-label="Open preview in right panel"]')!.click(); return null; });
    await tool("preview_act",{action:"upload",selector:"input",paths:[`${project}/report.txt `]});
    const result = await tool("preview_evaluate",{expression:`(async()=>{const f=document.querySelector('input').files[0];return {name:f.name,text:await f.text()}})()`});
    console.log("Upload result",JSON.stringify(result));
    await tool("preview_wait_for",{text: result.structuredContent.value.text});
    const snapshot = await tool("preview_snapshot",{save:true});
    console.log("Target snapshot", JSON.stringify(snapshot));
    await screen.getByText("Agent has control", {exact:true}).waitFor({timeout:30000});
    await browser.evaluate(() => {
      window.uploadProofFrame = new Promise<void>(resolve => {
        const draw = CanvasRenderingContext2D.prototype.drawImage;
        CanvasRenderingContext2D.prototype.drawImage = function(...args) {
          draw.apply(this, args);
          if (this.canvas.closest("[data-server-browser-surface]")) {
            CanvasRenderingContext2D.prototype.drawImage = draw;
            resolve();
          }
        };
      });
      return null;
    });
    await tool("preview_resize", {mode:"freeform",width:900,height:600});
    await browser.evaluate(() => window.uploadProofFrame.then(() => null));
    await app.screenshot("literal-upload-result");
    const serialized = JSON.stringify(result);
    expect(result.structuredContent.value).toEqual({name:"report.txt ",text:"intended"});
  } finally { process.kill(replayPid, "SIGCONT"); await new Promise<void>(r=>server.close(()=>r())); }
});
