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

test("Windows spaced GitHub ranges open like colon ranges", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("range-demo", {
    "src/a.ts": Array.from({length:30}, (_,i) => `// Sample line ${i+1}`).join("\n"),
    "C#/a.cs": "// C sharp\n".repeat(30),
    "(group)/[id]/+page.svelte": "<p>Routing sample</p>\n".repeat(30),
  });
  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: "Inline file ranges", messages: [
    'Compare inline references:\n\nRelative hash: `src/a.ts#L10-L20`\n\nRelative colon: `src/a.ts:10-20`\n\nSingle hash: `src/a.ts#L10`\n\nSingle colon: `src/a.ts:10`\n\nBare hash: `a.ts#L10-L20`\n\nBare colon: `a.ts:10-20`\n\nWindows hash: `C:\\My Files\\a.ts#L10-L20`\n\nWindows colon: `C:\\My Files\\a.ts:10-20`\n\nAmbiguous hash: `C#/a.cs#L10`\n\nRouting: `(group)/[id]/+page.svelte:10-20`\n\nMarkdown destination: [see range](src/a.ts#L10-L20)'
  ]});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Compare inline/).tap();
  const body = browser.locator("[data-user-message-body]");
  await body.getByText("Relative hash:", {exact:false}).waitFor();
  await app.screenshot("inline-reference-matrix");
  // Capture the actual click outcome on both sides, even when the hash is plain code.
  await body.getByText("Relative hash:", {exact:false}).tap();
  await browser.evaluate(() => {
    const body = document.querySelector('[data-user-message-body]');
    const code = [...(body?.querySelectorAll('code') ?? [])].find(e => e.textContent === 'C:\\My Files\\a.ts#L10-L20');
    if (code) code.click();
    else {
      const paragraph = [...(body?.querySelectorAll('p') ?? [])].find(e => e.textContent?.startsWith('Windows hash:'));
      const link = paragraph?.querySelector('a');
      link?.click();
    }
  });
  await app.screenshot("after-clicking-inline-hash");
  const candidates = await browser.evaluate(() => [...document.querySelectorAll('[data-user-message-body] a')].map(e=>({text:e.textContent,href:e.getAttribute('href')})));
  expect(candidates.filter(e=>e.href?.toLowerCase().includes('my files') && e.text?.includes('L10–20')).length).toBe(2);
  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('Sample line 10');
  await app.screenshot("windows-hash-range-file-opened");
});
