/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// This reproduction uses the question fixture described in the report; no live provider is needed.
const frame = (kind: string, method: string, rest = {}) => ({type: kind === "request" && method === "session/prompt" ? "expect_outbound" : "emit_inbound", frame: {kind, method, ...rest}});
const recording = [
 frame("request", "session/prompt"),
 frame("notification", "session/update", {params:{sessionId:"fixture",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"first fixture turn complete"}}}}),
 frame("response", "session/prompt", {result:{stopReason:"end_turn"}}),
 frame("request", "session/prompt"),
 frame("request", "elicitation/create", {params:{sessionId:"fixture",mode:"form",message:"Choose a color and size.",requestedSchema:{type:"object",properties:{
 color:{type:"string",title:"Which color?",oneOf:[{const:"red",title:"Red"},{const:"blue",title:"Blue"}]},
 color__other:{type:"string",title:"Other (type your own)"},
 size:{type:"string",title:"Which size?",enum:["Small","Large"]}
 },required:["size"]}}}),
 frame("notification", "session/update", {params:{sessionId:"fixture",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"Answers received."}}}}),
 frame("response", "session/prompt", {result:{stopReason:"end_turn"}}),
].map(x=>JSON.stringify(x)).join("\n");

test("Choosing Red sets aside a screenshot whose download is still pending", WEB, async ({t3,app,browser,screen})=>{
 const replay = await fs.readFile(new URL("../../apps/server/scripts/dev-replay-agent.ts",import.meta.url),"utf8");
 const project = await t3.project("Screenshot choices", {"replay/dev-replay-agent.ts":replay,"replay/dev-replay/showcase_transcript.ndjson":recording});
 const instanceId=ProviderInstanceId.make("screenshot-question-fixture");
 await runPromise(Effect.gen(function*(){
 const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
 yield* client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId,instance:{driver:ProviderDriverKind.make("acpRegistry"),displayName:"Question fixture",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[path.join(project,"replay/dev-replay-agent.ts")]}}}});
 }).pipe(Effect.scoped));
 const {cli}=makeState(T3_HOME);
 const started=await runPromise(cli(["thread","start",project,"hello","--title","Screenshot option download","--provider",instanceId,"--model","default","--wait","--json"]));
 await t3.open(JSON.parse(started.stdout));
 await screen.getByText("first fixture turn complete",{exact:false}).waitFor();
 const editor=browser.locator('[data-chat-composer-form="true"] [contenteditable="true"]');
 await editor.fill("Please inspect this screenshot.");
 await browser.evaluate(()=>{
 const canvas=document.createElement("canvas");canvas.width=640;canvas.height=360;
 const ctx=canvas.getContext("2d")!;ctx.fillStyle="#2563eb";ctx.fillRect(0,0,640,360);ctx.fillStyle="white";ctx.font="30px sans-serif";ctx.fillText("Screenshot for custom answer",35,180);
 return new Promise<void>(resolve=>canvas.toBlob(blob=>{const dt=new DataTransfer();dt.items.add(new File([blob!],"screenshot.png",{type:"image/png"}));document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:dt,bubbles:true,cancelable:true}));resolve();},"image/png"));
 });
 await browser.locator('button[aria-label="Preview screenshot.png"]:enabled').waitFor();
 await browser.keyboard.press("Enter");
 await screen.getByText("Which color?",{exact:true}).waitFor();
 // Reload drops the local attachment-byte cache, so copying the timeline message downloads its asset.
 await t3.open(JSON.parse(started.stdout));
 await screen.getByText("Which color?",{exact:true}).waitFor();
 await browser.evaluate(()=>{
 const clip:Record<string,string>={};(window as any).copied=clip;
 Object.defineProperty(navigator,"clipboard",{configurable:true,value:{write:async(items:ClipboardItem[])=>{for(const item of items)for(const type of item.types)clip[type]=await(await item.getType(type)).text();},writeText:async(text:string)=>{clip["text/plain"]=text;}}});
 });
 await screen.getByRole("button","Copy message",{exact:true}).last().tap();
 // Hold the actual fetch response, while letting the server supply the real screenshot bytes.
 await browser.evaluate(()=>{
 const original=window.fetch.bind(window);let release!:()=>void;const gate=new Promise<void>(r=>release=r);
 (window as any).downloadGate={release,started:false,finished:false};
 window.fetch=async(...args:Parameters<typeof fetch>)=>{const url=String(args[0]);const response=await original(...args);if(url.includes("/assets/")){(window as any).downloadGate.started=true;document.documentElement.dataset.downloadHeld="true";await gate;(window as any).downloadGate.finished=true;}return response;};
 });
 // Redact only the machine-local attachment path in the submitted timeline and recording.
 await browser.evaluate(()=>{
 const redact=()=>{const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(walker.nextNode()){const node=walker.currentNode;if(node.textContent && /"\/[^"\s]+"/.test(node.textContent))node.textContent=node.textContent.replace(/"\/[^"\s]+"/g,'"[attachment path redacted]"');}};
 new MutationObserver(redact).observe(document.body,{subtree:true,characterData:true,childList:true});
 });
 await editor.tap();
 await browser.evaluate(()=>{const dt=new DataTransfer();for(const [k,v]of Object.entries((window as any).copied))dt.setData(k,v as string);document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:dt,bubbles:true,cancelable:true}));});
 await browser.locator('html[data-download-held="true"]').waitFor();
 await app.screenshot("download-pending");
 await screen.getByRole("button",/^Red\b/).tap();
 await browser.evaluate(()=>{(window as any).downloadGate.release();});
 // A DOM marker observes completion without asserting away the bug.
 await browser.evaluate(async()=>{while(!(window as any).downloadGate.finished)await new Promise(r=>setTimeout(r,50));await new Promise(r=>setTimeout(r,500));document.documentElement.dataset.downloadReleased="true";});
 if(await screen.getByRole("button","Next",{exact:true}).count()) await screen.getByRole("button","Next",{exact:true}).tap();
 await screen.getByRole("button","Previous question",{exact:true}).tap();
 await app.screenshot("red-after-download-and-return");
 const attached=await browser.locator('[data-chat-composer-form="true"] button[aria-label="Preview screenshot.png"]').count();
 await screen.getByRole("button","Next",{exact:true}).tap();
 await screen.getByRole("button",/^Small\b/).tap();
 await screen.getByRole("button","Submit",{exact:true}).tap();
 await screen.getByText("Answers received.",{exact:false}).waitFor();
 await app.screenshot("submitted-answers");
 expect(attached,"The displaced custom screenshot must not attach to selected Red").toBe(0);
});
