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

test("Relative colon citation opens its literal workspace file at line 2", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("citation-demo", {
    "notes:final.txt": "first line\nsecond line of the colon file\nthird line\n",
    "notes.txt": "plain first line\nsecond line of plain notes\nthird line\n",
    "file:notes.txt": "Literal file-colon workspace document\n",
    "C:foo": "Drive-relative-shaped POSIX filename\n",
    "custom:/notes.txt": "Single slash scheme-shaped POSIX filename\n",
  });
  const primary = await t3.thread({project, title:"Colon filename citation", messages:['See :codex-file-citation{path="notes:final.txt" line_range_start="2"}']});
  const forms = ["notes.txt", "file:notes.txt", "C:foo", "custom:/notes.txt", `${project}/notes.txt`, `file://${project}/notes.txt`, `sandbox:${project}/notes.txt`, "https://example.com/notes.txt", "C:/notes.txt"];
  const controls = [];
  for (const path of forms) controls.push(await t3.thread({project, title:`Control ${controls.length+1}`, messages:[`See :codex-file-citation{path="${path}" line_range_start="2"}`]}));
  const explicit = await t3.thread({project, title:"Explicit relative control", messages:['See [notes:final.txt](<./notes:final.txt#L2>)']});
  const panel = () => browser.evaluate(() => {
    const panel = document.querySelector("[data-right-panel-surface-content]");
    for (const host of panel?.querySelectorAll("*") ?? []) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if(content) return {text:content.textContent, line:null};
    }
    return {text:panel?.textContent ?? "", line:null};
  });
  const observations = [];
  for (let i=0;i<controls.length;i++) {
    await t3.open(controls[i]);
    await screen.getByRole("button", /^Agent See/).tap();
    const links = await browser.evaluate(() => [...document.querySelectorAll(".chat-markdown a")].map(a => ({label:a.textContent, href:a.getAttribute("href")})));
    observations.push({path:forms[i].replaceAll(project,"<workspace>"),links:links.map(a=>({...a,href:a.href?.replaceAll(project,"<workspace>") ?? null}))});
    if(i>=7) await app.screenshot(`control-${i+1}-rendered`);
    if(i<7) {
      await browser.locator(".chat-markdown a").tap();
      await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 800)));
      await app.screenshot(`control-${i+1}-clicked`);
    }
  }
  await writeFile(new URL(`../.e2e/colon-observations-${Date.now()}.json`, import.meta.url), JSON.stringify(observations,null,2));
  await t3.open(explicit);
  await screen.getByRole("button", /^Agent See/).tap();
  await screen.getByRole("link", /^notes:final.txt/).tap();
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 800)));
  await app.screenshot("explicit-relative-opened");
  await t3.open(primary);
  await screen.getByRole("button", /^Agent See/).tap();
  await app.screenshot("colon-citation-rendered");
  await browser.locator(".chat-markdown a").tap();
  try {
    await expect.poll(async () => (await panel()).text).toContain("second line of the colon file");
  } finally {
    await app.screenshot("colon-citation-clicked");
  }
});
