import { expect } from "e2e";
import { execFileSync, spawn } from "node:child_process";
import { mkdirSync } from "node:fs";
import { test, WEB } from "./t3.ts";

test("External clipboard paste keeps terminal keyboard input in Firefox", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("clipboard-demo");
  await t3.thread({project, title:"Clipboard demonstration", messages:["Start"]});
  await t3.open();
  await screen.getByRole("button", "Clipboard demonstration, Done, clipboard-demo").tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await browser.locator('textarea[aria-label="Terminal input"]').waitFor({state:"attached"});
  await browser.evaluate(() => { (document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement).focus(); });
  await new Promise(r=>setTimeout(r,1200));
  execFileSync("xdotool", ["type","--clearmodifiers","--delay","60","unset PROMPT_COMMAND; PS1='terminal> '; clear"]);
  execFileSync("xdotool", ["key","Return"]);
  await new Promise(r=>setTimeout(r,800));
  const dir = `${process.env.T3_EVIDENCE_DIR}/${Date.now()}`;
  mkdirSync(dir, {recursive:true});
  execFileSync("xclip", ["-selection", "clipboard"], {input:"PASTED_ONCE", stdio:["pipe","ignore","ignore"]});
  await browser.evaluate(() => {
    (window as any).__typed = "";
    document.querySelector('textarea[aria-label="Terminal input"]')!.addEventListener("keydown", (e) => {if ((e as KeyboardEvent).key.length===1 && !(e as KeyboardEvent).ctrlKey) (window as any).__typed += (e as KeyboardEvent).key;});
  });
  const recording = spawn("ffmpeg", ["-y","-f","x11grab","-video_size","1290x900","-framerate","15","-i",process.env.DISPLAY!,"-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p",`${dir}/interaction.mp4`], {stdio:"ignore"});
  const stableCapture = async (name: string) => {
    for (let attempt=0; attempt<10; attempt++) {
      const first = execFileSync("import", ["-window","root","-crop","1290x900+0+0","rgb:-"], {maxBuffer: 8_000_000});
      await new Promise(r=>setTimeout(r,500));
      const second = execFileSync("import", ["-window","root","-crop","1290x900+0+0","rgb:-"], {maxBuffer: 8_000_000});
      if (first.equals(second)) {
        execFileSync("import", ["-window","root","-crop","1290x900+0+0",`${dir}/${name}.png`]);
        return;
      }
    }
    throw new Error("Desktop capture did not stabilize");
  };
  try {
    execFileSync("xdotool", ["key","ctrl+shift+v"]);
    await new Promise(r=>setTimeout(r,1600));
    await stableCapture("paste-prompt");
    execFileSync("xdotool", ["type","--clearmodifiers","--delay","150","_TYPED_AFTER"]);
    await new Promise(r=>setTimeout(r,800));
    await app.screenshot("after-paste-and-typing");
    await stableCapture("after-typing");
    await expect.poll(()=>browser.evaluate(()=>(window as any).__typed)).toBe("_TYPED_AFTER");
  } finally {
    recording.kill("SIGINT");
    await new Promise(r=>recording.once("exit",r));
    console.log(`Desktop captures: ${dir}`);
  }
});
