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

test("Explicit file URLs open extensionless files outside known roots", WEB, async ({ t3, app, browser, screen }) => {
  await mkdir("/nix/store/test/bin", { recursive: true });
  await writeFile("/nix/store/test/bin/tool", Array.from({ length: 30 }, (_, i) => `Tool documentation line ${i + 1}`).join("\n"));
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Extensionless file links", messages: ["Use [tool](file:///nix/store/test/bin/tool#L10-L20). Compare [tool](/nix/store/test/bin/tool:10-20). Ordinary [application route](/settings)."] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Use/).tap();
  await app.screenshot("file-links-rendered");
  // Exercise the explicit URL even on base, where it opens an app route in another tab.
  await screen.getByRole("link", /^tool/).first().tap();
  try {
    await expect.poll(() => 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 content.textContent ?? "";
      }
      return panel?.textContent ?? "";
    })).toContain("Tool documentation line 10");
    await expect.poll(() => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        if (host.shadowRoot?.querySelector('[data-line="10"][data-file-link-reveal]')) return true;
      }
      return false;
    })).toBe(true);
    await expect(screen.getByRole("link", "tool · L10–20").first()).toBeVisible();
    await expect(screen.getByRole("link", "application route")).toHaveAttribute("href", "/settings");
  } finally {
    await app.screenshot("explicit-file-clicked");
  }
});
