/// <reference lib="dom" />
import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Escaped spaces beside a literal percent open the cited file at line 10", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("t3-proof", {
    "My Folder/100%/notes.md": Array.from({length:30}, (_,i) => `Line ${i+1}: percent-path proof`).join("\n"),
  });
  const uri = `file://${project}/My%20Folder/100%/notes.md#L10-L20`;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({project, title:"Percent path file link", model:"multi-turn", messages:[`[note](${uri})`]});
  await t3.open(thread);
  // Deliberate reading time makes both interactions visible in the recording.
  const dwell = () => new Promise(resolve => setTimeout(resolve, 2500));
  const stableCapture = async (label: string) => {
    let previous = await readFile(await app.screenshot(`${label}-settling`));
    for (let attempt = 0; attempt < 8; attempt++) {
      await new Promise(resolve => setTimeout(resolve, 500));
      const current = await readFile(await app.screenshot(label));
      if (current.equals(previous)) return;
      previous = current;
    }
    throw new Error("Capture did not settle");
  };
  const expand = screen.getByRole("button", /^Agent/).filter({hasText:"note"});
  await expand.waitFor();
  await dwell();
  await expand.tap();
  const chip = screen.getByRole("link", /^notes\.md/);
  await chip.waitFor();
  await browser.evaluate(() => document.querySelector('a[href*="notes.md"]')?.scrollIntoView({block:"center"}));
  await dwell();
  await chip.hover();
  await dwell();
  await stableCapture("expanded-chip-L10-L20");
  await chip.tap();
  await dwell();
  await browser.evaluate(() => document.querySelector('a[href*="notes.md"]')?.scrollIntoView({block:"center"}));
  await dwell();
  // The file editor has a caret inside its shadow root; blur it for stable stills.
  await browser.evaluate(() => {
    let active = document.activeElement;
    while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
    if (active instanceof HTMLElement) active.blur();
    if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
  });
  await dwell();
  await stableCapture("percent-path-file-open");
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("Line 10: percent-path proof");
  expect(await chip.getAttribute("href")).toBe(`${project}/My Folder/100%/notes.md:10`);
});
