/// <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 SOURCE = "/tmp/factory-pr-44650-evidence-1/demo/src/Program.cs";
const EDITOR_ARGS = `${T3_HOME}/editor-args.txt`;
const read = (file: string) => runPromise(Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  return (yield* fs.exists(file)) ? yield* fs.readFileString(file) : "";
}));

test("A .NET stack frame opens Program.cs at line 29", WEB, async ({ t3, app, browser, screen }) => {
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(SOURCE.slice(0, SOURCE.lastIndexOf("/")), { recursive: true });
    yield* fs.writeFileString(SOURCE, Array.from({length: 40}, (_, i) => `// Demo source line ${i + 1}`).join("\n"));
    yield* fs.remove(EDITOR_ARGS, { force: true });
  }));
  const project = await t3.project("demo", {
    "print-frame.sh": `export PS1='$ '; clear; for i in $(seq 1 40); do printf '   at Demo.Program.Main(String[] args) in %s:line 29\\n' '${SOURCE}'; done; printf '\\ncontrol: %s:29\\n' '${SOURCE}'; echo ready > printed\n`,
  });
  const thread = await t3.thread({ project, title: ".NET stack trace", messages: ["Inspect this .NET stack trace"] });
  await browser.setViewport({width: 1800, height: 900});
  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='$ '; bash print-frame.sh\n");
  await expect.poll(() => read(`${project}/printed`), {timeout: 30000}).toBe("ready\n");
  const canvas = await browser.evaluate(() => {
    const box = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
    return box ? {x: box.x, y: box.y, height: box.height} : null;
  });
  if (!canvas) throw new Error("Terminal canvas missing");
  await browser.mouse.move(canvas.x + 450, canvas.y + canvas.height / 2);
  await browser.keyboard.down("Control");
  try {
    await expect.poll(() => browser.evaluate(() => {
      const canvas = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas");
      return canvas ? getComputedStyle(canvas).cursor : "missing";
    }), {timeout: 5000}).toBe("pointer");
  } finally {
    await app.screenshot("dotnet-frame-hover");
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.keyboard.up("Control");
    try {
      await expect.poll(() => read(EDITOR_ARGS), {timeout: 5000}).toBe(`--classic\n--goto\n${SOURCE}:29\n`);
    } finally {
      await app.screenshot("dotnet-frame-after-click");
    }
  }
});
