import { readFileSync, readdirSync, readlinkSync } from "node:fs";
import { createServer } from "node:http";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { test, WEB, runPromise } from "./t3.ts";

function credentialFor(threadId: string, project: string) {
  for (const pid of readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
    try {
      if (readlinkSync(`/proc/${pid}/cwd`) !== project) continue;
      const env = Object.fromEntries(readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").map((entry) => {
        const split = entry.indexOf("=");
        return [entry.slice(0, split), entry.slice(split + 1)];
      }));
      if (env.T3CODE_THREAD_ID === threadId && env.T3_ACP_MCP_AUTHORIZATION) {
        return { endpoint: env.T3_ACP_MCP_ENDPOINT!, authorization: env.T3_ACP_MCP_AUTHORIZATION };
      }
    } catch {}
  }
  throw new Error("Could not find this scenario thread's replay process MCP credential");
}

test("Hidden preview responses explain where the user's tab is", WEB, async ({ t3, app, browser, screen }) => {
  const page = createServer((_req, res) => res.end("<!doctype html><title>repro 49224</title><h1>Preview visibility reproduction</h1>"));
  await new Promise<void>((resolve) => page.listen(0, "127.0.0.1", resolve));
  try {
    const address = page.address();
    if (!address || typeof address === "string") throw new Error("No HTTP address");
    const project = await t3.project("preview-visibility");
    const a = await t3.thread({ project, title: "Thread A — on screen", messages: ["Reply with just OK"] });
    const b = await t3.thread({ project, title: "Thread B — preview owner", model: "question", messages: ["Prepare preview"] });
    await t3.open(a);
    await screen.getByRole("button", "Toggle right panel").waitFor();
    const credential = credentialFor(b.threadId, project);
    const results = await runPromise(Effect.gen(function* () {
      const session = yield* mcpToolSession({ ...credential, clientName: "preview-visibility-evidence" });
      const opened = yield* session.call("preview_open", { url: `http://127.0.0.1:${address.port}/`, open: true, reuseExistingTab: false });
      const openText = opened.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join("\n");
      const parsed = JSON.parse(openText);
      const status = yield* session.call("preview_status", { tabId: parsed.tabId });
      const statusText = status.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join("\n");
      return { open: parsed, status: JSON.parse(statusText) };
    }).pipe(Effect.scoped));
    // Evidence instrumentation: show verbatim protocol fields beside the real app, with no credentials or local paths.
    await browser.evaluate((responses) => {
      const aside = document.createElement("aside");
      aside.setAttribute("aria-label", "Captured MCP responses (evidence)");
      aside.style.cssText = "position:fixed;right:20px;bottom:20px;width:570px;max-height:80vh;overflow:auto;background:#111827;color:#f9fafb;padding:20px;border:2px solid #9ca3af;border-radius:10px;z-index:99999;font:15px/1.5 monospace;white-space:pre-wrap";
      aside.textContent = "EVIDENCE — actual MCP responses\nThread A on screen; caller owns Thread B\n\n" + Object.entries(responses).map(([name, result]) => `${name === "open" ? "preview_open(open: true)" : "preview_status"}\n${JSON.stringify({ available: result.available, visible: result.visible, title: result.title, notVisibleReason: result.notVisibleReason }, null, 2)}`).join("\n\n");
      document.body.append(aside);
    }, results);
    await app.screenshot("hidden-preview-responses");
    expect(results.open.visible).toBe(false);
    expect(results.open.notVisibleReason).toContain("thread's browser panel");
    expect(results.status.notVisibleReason).toContain("thread's browser panel");
  } finally {
    await new Promise<void>((resolve, reject) => page.close((error) => error ? reject(error) : resolve()));
  }
});
