/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { ScenarioError } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";
const searchOverMcp = Effect.fn("scenario.searchOverMcp")(function* (
  baseUrl: string,
  limit: number,
) {
  const { cli } = makeState(T3_HOME);
  const { stdout } = yield* cli([
    "auth",
    "session",
    "issue",
    "--subject",
    "mcp-client",
    "--scope",
    "orchestration:read",
    "--scope",
    "orchestration:operate",
    "--token-only",
  ]);
  const client = yield* HttpClient.HttpClient;
  let sessionId: string | null = null;
  const send = Effect.fnUntraced(function* (message: object) {
    const response = yield* client.execute(
      HttpClientRequest.post(`${baseUrl}/mcp`).pipe(
        HttpClientRequest.setHeaders({
          accept: "application/json, text/event-stream",
          authorization: `Bearer ${stdout.trim()}`,
          ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
        }),
        HttpClientRequest.bodyJsonUnsafe({ jsonrpc: "2.0", ...message }),
      ),
    );
    sessionId = response.headers["mcp-session-id"] ?? sessionId;
    const body = yield* response.text;
    if (response.status >= 300) {
      return yield* new ScenarioError({ message: `MCP ${response.status}: ${body}` });
    }
    return body;
  });
  yield* send({
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: "2025-06-18",
      capabilities: {},
      clientInfo: { name: "scenario", version: "1" },
    },
  });
  yield* send({ method: "notifications/initialized" });
  const result = yield* send({
    id: 2,
    method: "tools/call",
    params: { name: "t3_thread_search", arguments: { query: "heron", limit } },
  });
  if (result.includes('"isError":true')) {
    return yield* new ScenarioError({ message: `Search failed: ${result}` });
  }
  const payload = result.startsWith("data:") ? result.split("\n").filter((line) => line.startsWith("data: ")).map((line) => line.slice(6)).join("\n") : result;
  const rpc = JSON.parse(payload);
  return rpc.result.structuredContent ?? JSON.parse(rpc.result.content.find((part: {type: string}) => part.type === "text").text);
}, Effect.provide(FetchHttpClient.layer));

test("Thread search retains the five best title matches", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("heron-project");
  const threads = [];
  for (let i = 1; i <= 6; i++) {
    threads.push(await t3.thread({ project, title: `Heron ${i}`, messages: ["Start"] }));
  }
  for (const thread of threads) {
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    await composer.pressSequentially("a heron sighting");
    await composer.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: false }).waitFor({ state: "visible" });
  }
  const six = await runPromise(searchOverMcp(app.baseUrl ?? "", 6));
  const five = await runPromise(searchOverMcp(app.baseUrl ?? "", 5));
  await browser.evaluate(({six, five}) => {
    const panel = document.createElement("section");
    panel.style.cssText = "position:fixed;inset:60px 80px;z-index:999999;background:#121820;color:#edf2f7;padding:32px;font:18px/1.6 monospace;overflow:auto;border:1px solid #718096;border-radius:12px";
    const heading = document.createElement("h2");
    heading.textContent = 'Real server MCP: t3_thread_search("heron")';
    panel.append(heading);
    for (const [limit, result] of [[6, six], [5, five]] as const) {
      const title = document.createElement("h3"); title.textContent = `limit ${limit}`; panel.append(title);
      for (const match of result.matches) {
        const row = document.createElement("div"); row.textContent = `${match.title} — source=${match.source}${match.snippet ? ` — ${match.snippet}` : ""}`; panel.append(row);
      }
    }
    document.body.append(panel);
  }, {six, five});
  await app.screenshot("ranked-search-results");
  expect(five.matches.map((match: {threadId: string}) => match.threadId)).toEqual(six.matches.slice(0, 5).map((match: {threadId: string}) => match.threadId));
  expect(five.matches.map((match: {source: string}) => match.source)).toEqual(Array(5).fill("title"));
});
