/// <reference lib="dom" />
import { homedir } from "node:os";
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 editor = `${T3_HOME}/editor-args.txt`;
const read = (file: string) => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.exists(file).pipe(Effect.flatMap(exists => exists ? fs.readFileString(file) : Effect.succeed("")))));
test("Markdown bold terminal paths open the exact file and location", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo", {"src/main.ts": "// location proof\n".repeat(20)});
  const thread = await t3.thread({project, title: "Terminal paths", model: "default", messages: ["Ready"]});
  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 results: string[] = [];
  for (const [label, line] of [["plain-control", "./src/main.ts:12:3"], ["bold-absolute", "**/etc/hosts**"], ["bold-relative", "(**./src/main.ts:12:3**)"], ["bold-home", "**~/../../etc/hosts**."]] as const) {
    await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(editor, "")));
    await input.focus();
    await browser.keyboard.type(`export PS1=\'$ \'; clear; for i in $(seq 1 100); do printf '%s\\n' '${line}'; done; echo ready > ${label}.done\n`);
    await expect.poll(() => read(`${project}/${label}.done`)).toEqual("ready\n");
    const box = await browser.evaluate(() => {
      const b = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
      return b ? {x:b.x,y:b.y,height:b.height} : null;
    });
    if (!box) throw new Error("Terminal canvas absent");
    await browser.mouse.move(box.x + 400, box.y + box.height / 2);
    await browser.mouse.move(box.x + 65, box.y + box.height / 2);
    // Let terminal filesystem validation and hover debounce settle before capture/click.
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
    await app.screenshot(label + "-hover");
    await browser.keyboard.down("Control");
    await browser.mouse.down(); await browser.mouse.up();
    await browser.keyboard.up("Control");
    await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 700)));
    // A control proves the real editor launch path is connected before testing bold links.
    if (label === "plain-control") await expect.poll(() => read(editor)).toContain(":12:3");
    else {
      // The subsequent screenshot/browser round trip allows the real activation RPC to finish.
      await app.screenshot(label + "-activated");
      results.push(await read(editor));
    }
  }
  await expect.poll(async () => { results[2] = await read(editor); return results; }).toEqual([
    "--classic\n/etc/hosts\n",
    `--classic\n--goto\n${project}/src/main.ts:12:3\n`,
    `--classic\n${homedir()}/../../etc/hosts\n`,
  ]);
});
