import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const sources = ["https://news.ycombinator.com/", "https://example.com/source_(demo)"];
const cases = [
  { label: "running-search-web", title: "Running search_web", input: { query: "top story on Hacker News today" }, output: `Grounding: (${sources[0]}). Source: [${sources[1]}].` },
  { label: "title-web-search", title: "Web search", input: { query: "title web search query" }, output: `Source: ${sources[0]}.` },
  { label: "title-search-the-web", title: "search the web", input: { query: "title search the web query" }, output: `Source: ${sources[0]}.` },
  ...["web_search", "search_web", "web-search"].map((variant) => ({ label: `variant-${variant.replaceAll("_", "-")}-${variant === "web-search" ? "hyphen" : "underscore"}`, title: "Search", input: { variant, query: `variant ${variant} query` }, output: `Source: ${sources[0]}.` })),
  { label: "query-without-output", title: "Search", input: { query: "no matching workspace file" } },
  { label: "explicit-location", title: "Search", input: { query: "needle" }, locations: [{ path: "src/actual.ts", line: 1 }] },
  { label: "explicit-path", title: "Search", input: { path: "src/actual.ts", query: "needle" } },
  { label: "running-search-web-no-output", title: "Running search_web", input: { query: "top story on Hacker News today" } },
];

test("ACP web searches retain citations and never invent file hits", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const project = await t3.project("workspace", { "src/actual.ts": "export const needle = true;\n" });
  const threads = [];
  try {
    for (const c of cases) {
      const update = { sessionUpdate: "tool_call", toolCallId: c.label, kind: "search", title: c.title, status: "completed", rawInput: c.input, ...("output" in c ? { rawOutput: c.output } : {}), ...("locations" in c ? { locations: c.locations } : {}) };
      const transcript = [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
        { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update } } },
        { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Replay complete. Synthetic ACP payload; no live web request." } } } } },
        { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
      ].map((entry) => JSON.stringify(entry)).join("\n") + "\n";
      await writeFile(fixture, transcript);
      const thread = await t3.thread({ project, title: c.label, model: "showcase", messages: [`ACP replay: title=${JSON.stringify(c.title)}; input=${JSON.stringify(c.input)}${"locations" in c ? "; explicit location=src/actual.ts" : ""}. ${"output" in c ? "Raw output contains grounding citations." : "No raw output."}`] });
      threads.push({ ...thread, c });
    }
  } finally { await writeFile(fixture, original); }
  const observations = [];
  for (const thread of threads) {
    if (thread === threads[0]) await t3.open(thread);
    else {
      const environmentId = await browser.evaluate(() => location.pathname.split("/")[1]);
      await app.open(`/${environmentId}/${thread.threadId}`);
    }
    await screen.getByRole("button", /^Worked for /).tap();
    const row = browser.locator('[data-v2-item-type="file_search"], [data-v2-item-type="web_search"]');
    await row.waitFor({ state: "visible" });
    await row.tap();
    await screen.getByText("Replay complete. Synthetic ACP payload; no live web request.").waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...").waitFor({ state: "hidden" });
    await browser.locator("main .animate-spin").waitFor({ state: "hidden" });
    await app.screenshot(thread.c.label);
    observations.push(await browser.evaluate(() => {
      const row = document.querySelector('[data-v2-item-type="file_search"], [data-v2-item-type="web_search"]')!;
      return { type: row.getAttribute("data-v2-item-type"), links: [...row.querySelectorAll("a")].map(a => a.getAttribute("href")), files: [...row.querySelectorAll("li > span.font-mono")].map(e => e.textContent), text: row.textContent };
    }));
  }
  for (let i = 0; i < 6; i++) {
    expect(observations[i].type).toBe("web_search");
    expect(observations[i].links).toEqual(i === 0 ? sources : [sources[0]]);
    expect(observations[i].files).toEqual([]);
  }
  expect(observations[9].type).toBe("web_search");
  expect(observations[9].files).toEqual([]);
  expect(observations[9].links).toEqual([]);
  expect(observations[6].files).toEqual([]);
  for (let i = 7; i < 9; i++) expect(observations[i].files).toEqual(["workspace/src/actual.ts"]);
});
