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

async function readMessage(origin: string, threadId: string) {
  const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--subject", "mcp-client", "--scope", "orchestration:read", "--token-only"]));
  let session = "";
  const send = async (message: object) => {
    const response = await fetch(`${origin}/mcp`, {
      method: "POST",
      headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${issued.stdout.trim()}`, ...(session ? { "mcp-session-id": session } : {}) },
      body: JSON.stringify({ jsonrpc: "2.0", ...message }),
    });
    session = response.headers.get("mcp-session-id") ?? session;
    const body = await response.text();
    if (!response.ok) throw new Error(`MCP HTTP ${response.status}`);
    return body;
  };
  await send({ id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "proof", version: "1" } } });
  await send({ method: "notifications/initialized" });
  const raw = await send({ id: 2, method: "tools/call", params: { name: "t3_thread_read", arguments: { threadId, view: "messages" } } });
  const lines = raw.startsWith("data:") || raw.includes("\ndata:") ? raw.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()) : [raw];
  const response = lines.map(line => JSON.parse(line)).find(value => value.id === 2);
  if (response.error || response.result?.isError) throw new Error(`MCP read failed: ${JSON.stringify(response)}`);
  const data = response.result.structuredContent ?? JSON.parse(response.result.content.find((item: {type: string}) => item.type === "text").text);
  const message = data.items.find((item: {text: string | null}) => item.text?.startsWith("The signature check is in "))?.text;
  if (!message) throw new Error("MCP read omitted the target message");
  const side = APP_DIR.includes("18e4ac289f") ? "head" : "base";
  await writeFile(new URL(`../.e2e/prove/${side}-mcp-read.txt`, import.meta.url), `Real server MCP call: t3_thread_read, view=messages\nUser message text returned:\n${message}\n`);
  return message;
}

test("Thread search preserves ordinary api/hooks filenames", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Stripe signature verification", messages: ["Start"], model: "multi-turn" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.pressSequentially("The signature check is in app/api/hooks/stripe/verifySignature.ts");
  await composer.press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const read = await readMessage(app.baseUrl ?? "", thread.threadId);
  const search = screen.getByRole("combobox", "Search threads");
  await search.fill("signature check");
  await screen.getByRole("listbox", "Thread search results").waitFor();
  // Reveal the complete result snippet without changing its text.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '#sidebar-thread-search-results .truncate { white-space: normal; overflow: visible; overflow-wrap: anywhere; }';
    document.head.append(style);
    return null;
  });
  await app.screenshot("control-search");
  await search.fill("verifySignature");
  try {
    await expect(screen.getByRole("listbox", "Thread search results")).toContainText("verifySignature.ts");
    expect(read).toBe("The signature check is in app/api/hooks/stripe/verifySignature.ts");
  } finally {
    await app.screenshot("filename-search");
  }
});
