/// <reference lib="dom" />
import { readFile, writeFile, symlink, unlink } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Relative MSBuild diagnostics retain their location and literal filenames take priority", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("compiler-demo", {"src/Literal.cs(3,10)":"literal filename\n", "src/Literal.cs":"source file\n", "src/Program.cs":"class Program {\n  static void Main() {\n    int x = 1\n  }\n}\n"});
  const alias = "/tmp/factory-pr-46076-a1796045149-evidence-1/source";
  await unlink(alias).catch(()=>{});
  await symlink(project, alias);
  const thread = await t3.thread({project, title:"C# compiler diagnostics", messages:["hello"], 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", "");
  const read = async (file:string) => readFile(file,"utf8").catch(()=>"");
  await expect.poll(async()=>{
    await input.focus();
    await browser.keyboard.type("echo ready > ready\n");
    return read(`${project}/ready`);
  }, {timeout:30000}).toBe("ready\n");
  const results: string[][] = [];
  for (const [label, path] of [["relative", "src/Program.cs"], ["absolute", `${alias}/src/Program.cs`], ["literal", "src/Literal.cs"]]) {
    await writeFile(`${T3_HOME}/editor-args.txt`, "");
    await input.focus();
    await browser.keyboard.type(`PS1='$ '; clear; for i in $(seq 1 100); do printf '%s\\n' '${path}(3,10): error CS1002: ; expected'; done; touch '${label}.done'\n`);
    await expect.poll(()=>read(`${project}/${label}.done`),{timeout:30000}).toBe("");
    // Wait for the output marker through the filesystem, without asserting unrelated behavior.
    await expect.poll(async()=> {try {await readFile(`${project}/${label}.done`); return true;}catch{return false;}},{timeout:30000}).toBe(true);
    const box = await browser.evaluate(()=>{
      const r=document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.getBoundingClientRect();
      return r ? {x:r.x,y:r.y,w:r.width,h:r.height}:null;
    });
    if(!box) throw new Error("Missing terminal canvas");
    await browser.mouse.move(box.x+30, box.y+12);
    await browser.keyboard.down("Control");
    await expect.poll(()=>browser.evaluate(()=>document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector("canvas")?.style.cursor), {timeout:15000}).toBe("pointer");
    await app.screenshot(`${label}-hover`);
    await browser.mouse.down(); await browser.mouse.up();
    await browser.keyboard.up("Control");
    let opened: string[] = [];
    await expect.poll(async()=> {
      const args = (await read(`${T3_HOME}/editor-args.txt`)).trim().split("\n");
      if (args.some(arg=>arg.includes("/src/"))) opened = args;
      return opened.length > 0;
    }, {timeout:15000}).toBe(true);
    results.push(opened);
    await app.screenshot(`${label}-activated`);
  }
  expect(results).toEqual([
    ["--classic", "--goto", `${project}/src/Program.cs:3:10`],
    ["--classic", "--goto", `${alias}/src/Program.cs:3:10`],
    ["--classic", `${project}/src/Literal.cs(3,10)`],
  ]);
});
