import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Assistant Windows sandbox path spellings both render as file chips", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("sandbox-link-repro", { "t3-repro/sandbox-link-probe.md": "T3 FILE LINK PROBE" });
  const settingsPath = Path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await FS.readFile(settingsPath, "utf8"));
  settings.providerInstances.pi = { driver: "pi", enabled: true };
  await FS.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli([
    "thread", "start", project,
    "Reply with exactly these two Markdown paragraphs, verbatim, with no preamble or code fence:\n\nA [sandbox-link-probe.md](sandbox:C:/t3-repro/sandbox-link-probe.md)\n\nB [sandbox-link-probe.md](sandbox:/C:/t3-repro/sandbox-link-probe.md)",
    "--title", "Windows sandbox file links", "--provider", "pi", "--model", "anthropic/claude-haiku-5-5", "--wait", "--json",
  ]).pipe(Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 30, while: error => /not advertised|not enabled|not found/i.test(error.message) })));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open({ threadId });
  await screen.getByRole("link", "sandbox-link-probe.md").first().waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("assistant-windows-sandbox-file-links");
  const links = await browser.evaluate(() => Array.from(document.querySelectorAll('a')).filter(a => a.textContent?.includes("sandbox-link-probe.md")).map(a => ({ href: a.getAttribute("href"), chip: a.getAttribute("data-slot") === "context-chip" || !!a.querySelector('[data-slot="context-chip"]') })));
  expect(links).toEqual([
    { href: "C:/t3-repro/sandbox-link-probe.md", chip: true },
    { href: "C:/t3-repro/sandbox-link-probe.md", chip: true },
  ]);
});
