/// <reference lib="dom" />
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Completed question answers remain readable through MCP and text pagination", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("question-proof");
  const thread = await t3.thread({ project, title: "Completed user input", model: "question", messages: ["Ask one clarifying question"] });
  await t3.open(thread);
  await screen.getByRole("button", "Strict schemas (Recommended)", { exact: false }).tap();
  await screen.getByText("plan questions fixture complete", { exact: false }).waitFor();
  const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--subject", "mcp-client", "--scope", "orchestration:read", "--token-only"]));
  let session = "";
  let id = 0;
  const send = async (method: string, params?: object) => {
    const response = await fetch(`${app.baseUrl}/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", ...(method.startsWith("notifications/") ? {} : { id: ++id }), method, params }) });
    session = response.headers.get("mcp-session-id") ?? session;
    const raw = await response.text();
    if (!response.ok) throw new Error(`MCP ${response.status}: ${raw}`);
    if (!raw) return null;
    return JSON.parse(raw.startsWith("event:") || raw.startsWith("data:") ? raw.split("\n").find(line => line.startsWith("data:"))!.slice(5) : raw);
  };
  await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "proof", version: "1" } });
  await send("notifications/initialized");
  const read = async (extra = {}) => {
    const reply = await send("tools/call", { name: "t3_thread_read", arguments: { threadId: thread.threadId, view: "activity", maxCharsPerItem: 10000, ...extra } });
    if (reply.error || reply.result.isError) throw new Error(JSON.stringify(reply));
    return reply.result.structuredContent ?? JSON.parse(reply.result.content.find((c: any) => c.type === "text").text);
  };
  const full = await read();
  const item = full.items.find((i: any) => i.type === "user_input_request");
  if (!item) throw new Error(`No input item: ${JSON.stringify(full)}`);
  let offset = 0;
  let reconstructed = "";
  const pages = [];
  do {
    const page = await read({ itemId: item.itemId, maxCharsPerItem: 80, textOffset: offset });
    const part = page.items.find((i: any) => i.itemId === item.itemId);
    pages.push({ offset, text: part.text, nextTextOffset: part.nextTextOffset });
    reconstructed += part.text;
    if (part.nextTextOffset == null) break;
    offset = part.nextTextOffset;
  } while (pages.length < 50);
  const display = `t3_thread_read(view: "activity")
Item: ${item.type} | Status: ${item.status}

${item.text}

Pagination: maxCharsPerItem=80, ${pages.length} pages
Offsets: ${pages.map(p => p.offset).join(", ")}
Reconstructed answers: ${JSON.stringify(JSON.parse(reconstructed).answers ?? null)}
Reconstructed text matches full read: ${reconstructed === item.text}`;
  await browser.evaluate((text) => {
    const panel = document.createElement("pre");
    panel.style.cssText = "position:fixed;inset:16px;z-index:99999;background:#111827;color:#e5e7eb;padding:24px;overflow:auto;font:13px/1.3 monospace;white-space:pre-wrap;border:2px solid #64748b";
    panel.textContent = "LIVE MCP RESPONSE — completed user input\n\n" + text;
    document.body.append(panel);
    return null;
  }, display);
  await app.screenshot("completed-input-mcp-response");
  expect(JSON.parse(item.text).answers).toEqual({ schema_vs_ui_flexibility: "Strict schemas (Recommended)" });
  expect(reconstructed).toBe(item.text);
});
