/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Inline absolute paths preserve consecutive spaces and line ranges", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const lines = Array.from({ length: 30 }, (_, i) => `Line ${i + 1}`).join("\n");
  const project = await t3.project("spaced", { "My  Folder/notes.md": lines, "My Folder/notes.md": lines });
  const publicRoot = `/tmp/factory-pr-46241-a1796061148-evidence-1/demo-${Date.now()}`;
  await fs.symlink(project, publicRoot);
  const paths = [String.raw`C:\My  Folder\notes.md#L10-L20`, String.raw`C:\My Folder\notes.md#L10-L20`, `${publicRoot}/My  Folder/notes.md#L10-L20`, `${publicRoot}/My Folder/notes.md#L10-L20`, String.raw`\\server\Team  Share\notes.md#L10-L20`, String.raw`\\server\Team Share\notes.md#L10-L20`];
  const labels = ["Drive — consecutive spaces", "Drive — single space", "Existing POSIX — consecutive spaces", "Existing POSIX — single space", "UNC outside matching share — consecutive spaces", "UNC outside matching share — single space"];
  const reply = "Compare inline paths\n\n" + paths.map((p, i) => `${labels[i]}: \`${p}\``).join("\n\n") + "\n\nEnd of path comparison.";
  const transcript = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(transcript, "utf8");
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.writeFile(transcript, frames.map((f) => JSON.stringify(f)).join("\n") + "\n");
    const settingsPath = path.join(T3_HOME, "userdata/settings.json");
    const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
    settings.providerInstances.devReplay.config.customModels = ["showcase"];
    await fs.writeFile(settingsPath, JSON.stringify(settings));
    const { cli } = makeState(T3_HOME);
    let thread: { threadId: string } | undefined;
    for (let attempt = 0; attempt < 8 && !thread; attempt++) {
      const result = await runPromise(cli(["thread", "start", project, "Compare the six inline paths.", "--title", "Inline file paths", "--provider", "devReplay", "--model", "showcase", "--wait", "--json"], [0, 1]));
      if (result.stdout.includes('"threadId"')) thread = JSON.parse(result.stdout);
      else if (attempt === 7) throw new Error(result.stderr);
    }
    if (!thread) throw new Error("Thread not created");
    await t3.open(thread);
    await screen.getByText("End of path comparison.", { exact: true }).waitFor({ timeout: 60000 });
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden", timeout: 60000 });
    await app.screenshot("inline-path-comparison");
    const chips = await browser.evaluate(() => Array.from(document.querySelectorAll(".chat-markdown-file-link")).map((el) => ({ text: el.textContent, copy: el.closest("[data-markdown-copy]")?.getAttribute("data-markdown-copy") ?? el.getAttribute("data-markdown-copy") })));
    expect(chips.filter((c) => c.copy?.includes("My  Folder") && c.copy?.includes("#L10-L20")).length).toBe(2);
  } finally {
    await fs.writeFile(transcript, original);
  }
});
