/// <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) : "";
}));

test("Terminal wrapper punctuation leaves clean URL and file targets", WEB, async ({t3, app, browser, screen}) => {
  const line = "See (https://example.com/docs.) (see ./src/index.ts:12.)";
  const project = await t3.project("demo-project", {
    "src/index.ts": Array.from({length: 20}, (_, i) => `// Line ${i + 1}`).join("\n"),
    "links.txt": `${line}\n`.repeat(100),
  });
  let thread;
  for (let attempt = 0; attempt < 20; attempt++) {
    try {
      thread = await t3.thread({project, title: "Terminal sentence punctuation", messages: ["hello"], model: "multi-turn"});
      break;
    } catch (error) {
      if (attempt === 19 || !String(error).includes("not advertised")) throw error;
    }
  }
  if (!thread) throw new Error("Replay thread did not start");
  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("export PS1='$ '; clear; cat links.txt; echo done > printed.done\n");
  await expect.poll(() => read(`${project}/printed.done`)).toBe("done\n");
  await browser.evaluate(() => {
    document.body.dataset.openedUrl = "";
    window.open = ((url: string | URL | undefined) => { document.body.dataset.openedUrl = String(url); return null; }) as typeof window.open;
  });
  const canvas = await browser.evaluate(() => {
    const canvas = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas");
    if (!canvas) throw new Error("No terminal canvas");
    const b = canvas.getBoundingClientRect();
    const context = canvas.getContext("2d")!;
    return {x:b.x, y:b.y, height:b.height, cell:context.measureText("M").width};
  });
  const click = async (column: number) => {
    await browser.mouse.move(canvas.x + canvas.cell * column, canvas.y + canvas.height / 2);
    await browser.keyboard.down("Control");
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1000)));
    await app.screenshot(column < 30 ? "url-hover" : "file-hover");
    await browser.mouse.down(); await browser.mouse.up();
    await browser.keyboard.up("Control");
  };
  await click(15);
  const url = await browser.evaluate(() => document.body.dataset.openedUrl);
  await click(43);
  await app.screenshot("after-file-click");
  await expect.poll(async () => ({url, editor: (await read(`${T3_HOME}/editor-args.txt`)).trim().split("\n")})).toEqual({url:"https://example.com/docs", editor:["--classic", "--goto", `${project}/src/index.ts:12`]});
});
