/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";
const io = <A>(f: (fs: FileSystem.FileSystem) => Effect.Effect<A, unknown>) => runPromise(Effect.flatMap(FileSystem.FileSystem, f));
const read = (path: string) => io(asyncFs => Effect.gen(function* () { return (yield* asyncFs.exists(path)) ? yield* asyncFs.readFileString(path) : "MISSING"; }));
test("Explicit terminal file URIs preserve numeric filename suffixes", WEB, async ({ t3, app, browser, screen }) => {
  const receipt = `${T3_HOME}/editor-args.txt`;
  await io(fs => fs.writeFileString(`${T3_HOME}/bin/cursor`, `#!/bin/sh\nlast=''\nfor arg do last="$arg"; done\nprintf '%s\\n' "$last" > '${receipt}'\n`));
  const files: Record<string,string> = { "report.txt": "UNSUFFIXED FILE\n", "report.txt:12-64": "EXACT RANGE FILENAME\n", "report.txt:0": "EXACT ZERO FILENAME\n" };
  for (let i=0;i<4;i++) {
    const name = i%2===0 ? "report.txt:12-64" : "report.txt:0";
    files[`print-${i}.sh`] = `${i===2 ? "rm report.txt\n" : ""}clear\nprintf 'Ctrl+click a literal filename: ${name} (${i<2 ? "unsuffixed file exists" : "unsuffixed file absent"})\\n'\nfor i in $(seq 1 100); do command ls -d --hyperlink=always --color=never -1 --quoting-style=literal -- '${name}' | sed -E 's@file://[^/]+/@file:///@'; done\ntouch printed-${i}\n`;
  }
  const project = await t3.project("demo", files);
  const thread = await t3.thread({ project, title: "Terminal file links", messages: ["Show terminal file links"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input=screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  const actual: string[]=[];
  for(let i=0;i<4;i++) {
    await io(fs => fs.remove(receipt, {force:true}));
    await input.focus();
    await browser.keyboard.type(`export PS1='demo$ '; bash print-${i}.sh\n`);
    await expect.poll(()=>read(`${project}/printed-${i}`)).toEqual("");
    const canvas=await browser.evaluate(()=> { const b=document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector('canvas')?.getBoundingClientRect();return b?{x:b.x,y:b.y,h:b.height}:null; });
    if(!canvas) throw Error('Terminal canvas missing');
    await browser.mouse.move(canvas.x+16, canvas.y+canvas.h/2-(i%2)*40);
    await browser.keyboard.down('Control'); await browser.mouse.down(); await browser.mouse.up(); await browser.keyboard.up('Control');
    // Let the external editor launch finish, then show its actual argument in the real terminal.
    await input.focus();
    await io(fs => fs.writeFileString(`${project}/show-${i}.sh`, `sleep 2
printf '\\nEDITOR RECEIVED: '
if test -f '${receipt}'; then x=$(cat '${receipt}'); printf '%s\\n' "\u0024{x##*/}"; else echo 'NO ACTIVATION'; fi
touch shown-${i}
`));
    await browser.keyboard.type(`bash show-${i}.sh\n`);
    await expect.poll(()=>read(`${project}/shown-${i}`)).toEqual("");
    actual.push((await read(receipt)).trim().replace(project+'/', ''));
    await app.screenshot(`case-${i}-${i%2===0?'range':'zero'}-${i<2?'present':'absent'}`);
  }
  await expect(actual).toEqual(['report.txt:12-64','report.txt:0','report.txt:12-64','report.txt:0']);
});
