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

const cases = [
  { id: "literal-css", name: "Literal CSS", css: '[data-chat-header]::before { content: "/*"; } /* note */ [data-chat-header]::after { content: "@import"; }' },
  { id: "literal-control", name: "Literal Control", css: '[data-chat-header]::after { content: "@import"; }' },
  { id: "literal-escape", name: "Literal Escape", css: '[data-chat-header]::before { content: "\\" @import"; }' },
  { id: "remote-import", name: "Remote Import", css: '@import "https://example.invalid/theme.css";' },
  { id: "remote-url", name: "Remote URL", css: '[data-chat-header] { background: url("https://example.invalid/image.png"); }' },
];

test("MCP publishes CSS strings containing comment markers and escaped quotes", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("theme-proof", { "theme-results.txt": "MCP calls pending" });
  const thread = await t3.thread({ project, title: "Literal CSS theme proof", messages: ['Theme publishing results: :codex-file-citation{path="theme-results.txt" line_range_start="1"}'] });
  await t3.open(thread);
  const token = await browser.evaluate(async () => {
    const post = async (path: string, data: unknown) => {
      const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(data) });
      const json = await r.json();
      if (!r.ok) throw new Error(`${path}: ${JSON.stringify(json)}`);
      return json;
    };
    const redirect = "http://127.0.0.1:19876/callback";
    const verifier = "scenario-theme-css-proof-verifier-01234567890123456789";
    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
    const challenge = btoa(String.fromCharCode(...digest)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
    const registered = await post("/oauth/mcp/register", { client_name: "Theme CSS proof", redirect_uris: [redirect], token_endpoint_auth_method: "none" });
    const authorization = { response_type: "code", client_id: registered.client_id, redirect_uri: redirect, code_challenge: challenge, code_challenge_method: "S256" };
    const approval = await post("/oauth/mcp/approval", authorization);
    const decision = await post("/oauth/mcp/decision", { authorization, decision: { _tag: "browser-session", access: "full-access", csrfToken: approval.csrfToken } });
    const code = new URL(decision.redirectTo).searchParams.get("code")!;
    const r = await fetch("/oauth/mcp/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirect, client_id: registered.client_id, code_verifier: verifier }) });
    const token = await r.json();
    if (!r.ok) throw new Error("MCP authorization failed");
    return token.access_token as string;
  });
  let session: string | null = null;
  let id = 0;
  const send = async (method: string, params?: unknown, notification = false) => {
    const response = await fetch(`${app.baseUrl}/mcp`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}`, ...(session ? { "mcp-session-id": session } : {}) }, body: JSON.stringify({ jsonrpc: "2.0", ...(notification ? {} : { id: ++id }), method, ...(params ? { params } : {}) }) });
    session = response.headers.get("mcp-session-id") ?? session;
    const body = await response.text();
    if (!response.ok) throw new Error(`MCP ${response.status}: ${body}`);
    return body;
  };
  await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "theme-proof", version: "1" } });
  await send("notifications/initialized", undefined, true);
  await expect.poll(() => browser.evaluate(() => !!document.querySelector("[data-chat-header]"))).toBe(true);
  await expect.poll(() => browser.evaluate(() => !document.body.textContent?.includes("Syncing messages"))).toBe(true);
  const results: Array<{id: string; accepted: boolean; response: string}> = [];
  for (const item of cases) {
    const response = await send("tools/call", { name: "t3_theme_set", arguments: { themeId: item.id, theme: { name: item.name, appearance: "dark", canvas: "#1a1b26", accent: "#7aa2f7", css: item.css } } });
    const accepted = response.includes('"published":true') || response.includes('\\"published\\":true');
    results.push({ id: item.id, accepted, response });
    // Wait for the real environment-theme event to reach the connected client.
    if (accepted) await expect.poll(() => browser.evaluate(() => document.documentElement.classList.contains("dark"))).toBe(true);
    await app.screenshot(item.id);
  }
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Add theme", { exact: true }).waitFor({ state: "visible" });
  await browser.evaluate(() => {
    const cards = [...document.querySelectorAll("button")].filter((el) => el.getAttribute("aria-label")?.startsWith("Use Literal"));
    cards.at(-1)?.scrollIntoView({ block: "center" });
  });
  await app.screenshot("published-themes");
  const transcript = [
    "t3_theme_set: actual server replies",
    "",
    ...results.flatMap(({id, response}) => {
      const result = JSON.parse(response).result;
      const reply = JSON.parse(result.content[0].text);
      return [id, JSON.stringify(reply), ""];
    }),
  ].join("\n");
  await writeFile(`${project}/theme-results.txt`, transcript);
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Theme publishing results/).tap();
  await screen.getByRole("link", /^theme-results\.txt/).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("t3_theme_set: actual server replies");
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
  await app.screenshot("mcp-server-replies");
  console.log("Theme MCP results", JSON.stringify(results));
  expect(results.map(({id, accepted}) => ({id, accepted}))).toEqual(cases.map((item, i) => ({ id: item.id, accepted: i < 3 })));
});
