/// <reference lib="dom" />
// The DOM lib types the function this scenario runs in the page.
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_ARGS = `${T3_HOME}/editor-args.txt`;

/** The file's lines, or none while it does not exist. */
const readLines = (file: string) =>
  runPromise(
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      if (!(yield* fs.exists(file))) return [];
      return (yield* fs.readFileString(file)).trim().split("\n");
    }),
  );

test(
  "Ctrl+click on a Python traceback frame opens its reported line",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.remove("/tmp/python-traceback-proof-46505", { recursive: true, force: true })));
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) => fs.remove(EDITOR_ARGS, { force: true })),
    );
    const project = await t3.project("python-demo", {
      "app.py": "import helper\n\n\n\n\ndef main():\n    helper.explode()\n\n\nmain()\n",
      "helper.py": "def explode():\n    value = 1\n    value += 1\n    value += 1\n    value += 1\n    raise RuntimeError('traceback proof')\n",
      "run.sh": "proof_workspace=$PWD; mkdir -p /tmp/python-traceback-proof-46505; cp app.py helper.py show-editor.py /tmp/python-traceback-proof-46505/; cd /tmp/python-traceback-proof-46505; export PS1='$ '; clear; python3 app.py; touch \"$proof_workspace/cat.done\"\n",
      "show-editor.py": "import pathlib\nargs = pathlib.Path(" + JSON.stringify(EDITOR_ARGS) + ").read_text().splitlines()\nprint('Editor received: cursor ' + ' '.join(args))\n",
    });
    const thread = await t3.thread({ project, title: "Build", messages: ["Build it"] });
    await t3.open(thread);

    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const input = screen.getByRole("textbox", "Terminal input");
    // The input mounts before fonts and WASM finish loading and its handlers are installed.
    await expect(input).toHaveAttribute("data-workspace-focus-default", "");
    await input.focus();
    await browser.keyboard.type("source run.sh\n");
    await expect.poll(() => readLines(`${project}/cat.done`)).not.toEqual([]);
    await app.screenshot("traceback-printed");
    const canvas = await browser.evaluate(() => {
      const box = document.querySelector('[aria-label="Terminal input"]')
        ?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
      return box ? { x: box.x } : null;
    });
    if (!canvas) throw new Error("The terminal canvas is not on the page.");
    const results: string[][] = [];
    for (const [index, frame] of [
      { label: "app-line-7", y: 587, command: "clear; python3 app.py" },
      { label: "helper-line-6", y: 623, command: "clear; python3 app.py" },
      { label: "app-line-10", y: 551, command: "clear; python3 app.py" },
      { label: "colon-line-7-control", y: 533, command: "clear; echo /tmp/python-traceback-proof-46505/app.py:7" },
    ].entries()) {
      if (index > 0) {
        await input.focus();
        await browser.keyboard.type(`${frame.command}; touch ready-${index}\n`);
        await expect.poll(() => readLines(`/tmp/python-traceback-proof-46505/ready-${index}`)).not.toEqual([]);
      }
      await app.screenshot(`${frame.label}-printed`);
      await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.remove(EDITOR_ARGS, { force: true })));
      await browser.mouse.move(canvas.x + 110, frame.y);
      await browser.keyboard.down("Control");
      await app.screenshot(`${frame.label}-hover`);
      await browser.mouse.down();
      await browser.mouse.up();
      await browser.keyboard.up("Control");
      await expect.poll(async () => (await readLines(EDITOR_ARGS))[0]).toEqual("--classic");
      results.push(await readLines(EDITOR_ARGS));
      await input.focus();
      await browser.keyboard.type("python3 show-editor.py\n");
      await app.screenshot(`${frame.label}-editor-received`);
    }
    await expect(results).toEqual([
      ["--classic", "--goto", "/tmp/python-traceback-proof-46505/app.py:7"],
      ["--classic", "--goto", "/tmp/python-traceback-proof-46505/helper.py:6"],
      ["--classic", "--goto", "/tmp/python-traceback-proof-46505/app.py:10"],
      ["--classic", "--goto", "/tmp/python-traceback-proof-46505/app.py:7"],
    ]);
  },
);
