/// <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 read = (file: string) => runPromise(Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  return (yield* fs.exists(file)) ? yield* fs.readFileString(file) : "";
}));
const pause = () => runPromise(Effect.sleep("4 seconds"));

test("Bash bare script diagnostics link to line 3 and preserve dot-slash links", WEB, async ({t3,app,browser,screen}) => {
  const project = await t3.project("bash-diagnostics", {"run.sh": ":\n:\nscout_nonexistent_command_xyz\n"});
  const thread = await t3.thread({project,title:"Bash script diagnostics",messages:["Inspect the terminal diagnostics"],model:"default"});
  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", "");
  await input.focus();
  await browser.keyboard.type("PS1=''; printf '\\033[2J\\033[H'; LC_ALL=C bash run.sh; LC_ALL=C bash ./run.sh; echo done > bash.done\n");
  await expect.poll(()=>read(`${project}/bash.done`)).toEqual("done\n");
  await pause();
  const box = await browser.evaluate(()=>{
    const c=document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector('canvas');
    const b=c?.getBoundingClientRect();
    return b ? {x:b.x,y:b.y,width:b.width,height:b.height} : null;
  });
  if(!box) throw new Error("Missing terminal canvas");
  await browser.keyboard.down("Control");
  // Default terminal font is 12px with 16px rows and 4px padding.
  await browser.mouse.move(box.x+24,box.y+28);
  await pause();
  await app.screenshot("ctrl-hover-dot-slash-comparison");
  await browser.mouse.down(); await browser.mouse.up();
  await browser.keyboard.up("Control");
  await pause();
  const comparison=await read(`${T3_HOME}/editor-args.txt`);
  await runPromise(Effect.flatMap(FileSystem.FileSystem,fs=>fs.remove(`${T3_HOME}/editor-args.txt`,{force:true})));
  await browser.keyboard.down("Control");
  await browser.mouse.move(box.x+24,box.y+12);
  await pause();
  await app.screenshot("ctrl-hover-bare-script");
  await browser.mouse.down(); await browser.mouse.up();
  await browser.keyboard.up("Control");
  await pause();
  const bare=await read(`${T3_HOME}/editor-args.txt`);
  await expect({comparison:comparison.trim().split('\n'),bare:bare.trim().split('\n')}).toEqual({
    comparison:["--classic","--goto",`${project}/run.sh:3`],
    bare:["--classic","--goto",`${project}/run.sh:3`]
  });
});
