import { expect } from "e2e";
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

test("MCP embedded CSV downloads retain the URI basename before query and fragment", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Report exports");
  const attachmentId = "report-00000000-0000-4000-8000-000000000001-html";
  const html = `<!doctype html><html><head><style>body{font:16px system-ui;padding:20px;background:#fff;color:#18181b}button{padding:10px;margin:8px}small{display:block}</style></head><body><h2>Report exporter</h2><p id="status">initializing</p><button id="query">Download (?version=2)</button><button id="fragment">Download (#page=2)</button><small>Unnamed embedded resource: report.csv</small><script>
let seq=1;function send(method,params){parent.postMessage({jsonrpc:'2.0',id:seq++,method,params},'*')}
addEventListener('message',e=>{if(e.data.id===1&&e.data.result){document.querySelector('#status').textContent='ready';parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/initialized'},'*')}});
send('ui/initialize',{protocolVersion:'2026-01-26',appInfo:{name:'report-exporter',version:'1'},appCapabilities:{}});
for(const [id,suffix] of [['query','?version=2'],['fragment','#page=2']])document.getElementById(id).onclick=()=>send('ui/download-file',{contents:[{type:'resource',resource:{uri:'https://example.invalid/report.csv'+suffix,mimeType:'text/csv',text:'name,value\\nexample,2\\n'}}]});
</script></body></html>`;
  await mkdir(join(T3_HOME,"userdata/attachments"),{recursive:true});
  await writeFile(join(T3_HOME,"userdata/attachments",attachmentId+".html"),html);
  const fixture = join(APP_DIR,"apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture,"utf8");
  const update = (u:unknown)=>({type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:u}}});
  const transcript = [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    update({sessionUpdate:"tool_call",toolCallId:"export",kind:"other",title:"open_report_exporter",status:"in_progress",rawInput:{server:"report-exporter",tool:"open_report_exporter",arguments:{}},_meta:{is_mcp_tool_call:true}}),
    update({sessionUpdate:"tool_call_update",toolCallId:"export",status:"completed",rawOutput:{t3McpApp:{attachmentId,server:"report-exporter",tool:"open_report_exporter",resourceUri:"ui://report-exporter/app.html"}}}),
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
  ].map(x=>JSON.stringify(x)).join("\n");
  let thread;
  try { await writeFile(fixture,transcript); thread = await t3.thread({project,title:"CSV report downloads",messages:["Call open_report_exporter once."],model:"showcase"}); }
  finally {await writeFile(fixture,original);}
  await t3.open(thread);
  const frame = browser.frameLocator("iframe[title]");
  await frame.getByText("ready",{exact:true}).waitFor({state:"visible"});
  const names:string[]=[];
  const prompts:string[]=[];
  for (const [label,button] of [["query-download","Download (?version=2)"],["fragment-download","Download (#page=2)"]]) {
    await frame.getByRole("button",button).tap();
    await screen.getByRole("button","Confirm",{exact:true}).waitFor({state:"visible"});
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
    prompts.push(await browser.evaluate(()=>document.body.innerText));
    await app.screenshot(label);
    const download = await browser.waitForDownload(()=>screen.getByRole("button","Confirm",{exact:true}).tap());
    names.push(download.suggestedFilename);
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {}))); return null; });
  }
  await app.screenshot("downloads-complete");
  expect(names).toEqual(["report.csv","report.csv"]);
  for(const prompt of prompts) expect(prompt).toContain("Save report.csv from report-exporter?");
});
