// @effect-diagnostics nodeBuiltinImport:off -- Stage git fixtures and observe the real replay transport.
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

function client(endpoint: string, authorization: string) {
  let session: string | null = null;
  let id = 0;
  const send = async (method: string, params?: object, notification = false) => {
    const response = await fetch(endpoint, {
      method: "POST",
      headers: { accept: "application/json, text/event-stream", "content-type": "application/json", authorization, ...(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 raw = await response.text();
    if (!response.ok) throw new Error(`MCP HTTP ${response.status}: ${raw}`);
    if (!raw) return null;
    const data = raw.startsWith("data:") || raw.includes("\ndata:") ? raw.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("") : raw;
    const result = JSON.parse(data);
    return result.result ?? result.error;
  };
  return {
    init: async () => { await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "repository-proof", version: "1" } }); await send("notifications/initialized", undefined, true); },
    call: (name: string, args: object) => send("tools/call", { name, arguments: args }),
  };
}
const decoded = (result: any) => result.structuredContent ?? JSON.parse(result.content.find((c: any) => c.type === "text").text);
const text = (result: any) => result.content?.filter((c: any) => c.type === "text").map((c: any) => c.text).join("\n") ?? JSON.stringify(result);

test("MCP resolves issue and pull request targets from tracked repositories", WEB, async ({ t3, app, screen }) => {
  const seed = await t3.project("Repository group");
  const fixture = await fs.mkdtemp("/tmp/factory-issue-45382-evidence-2/run-");
  const group = path.join(fixture, "group");
  await fs.mkdir(group);
  for (const name of ["t3code", "uploadthing"]) {
    const checkout = path.join(fixture, `checkout-${name}`);
    await fs.mkdir(checkout);
    execFileSync("git", ["init", "--quiet", checkout]);
    execFileSync("git", ["-C", checkout, "remote", "add", "origin", `https://github.com/pingdotgg/${name}.git`]);
    await fs.symlink(checkout, path.join(group, name));
  }
  const { cli } = makeState(T3_HOME);
  const token = await runPromise(cli(["auth", "session", "issue", "--subject", "mcp-client", "--scope", "orchestration:read", "--scope", "orchestration:operate", "--token-only"]));
  const outside = client(`${app.baseUrl}/mcp`, `Bearer ${token.stdout.trim()}`);
  await outside.init();
  const listed = decoded(await outside.call("t3_project_list", {}));
  const project = listed.projects.find((p: any) => p.workspaceRoot === seed);
  const userToken = await runPromise(cli(["auth", "session", "issue", "--token-only"]));
  const updated = await fetch(`${app.baseUrl}/api/projects/mutate`, {
    method: "POST", headers: { authorization: `Bearer ${userToken.stdout.trim()}`, "content-type": "application/json" },
    body: JSON.stringify({ type: "project.update", commandId: crypto.randomUUID(), projectId: project.id, workspaceRoot: group, trackedFolders: ["t3code", "uploadthing"].map(name => ({ path: path.join(group, name), name })) }),
  });
  if (!updated.ok) throw new Error(`Project setup: ${await updated.text()}`);

  // This transparent relay preserves every real replay response and observes only its MCP config.
  const wrapper = path.join(seed, "observe-replay.mjs");
  const configFile = path.join(seed, "session-mcp.json");
  await fs.writeFile(wrapper, `import { spawn } from 'node:child_process';\nimport { writeFileSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nconst child = spawn(process.execPath, [${JSON.stringify(path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"))}], { stdio: ['pipe', 'pipe', 'inherit'] });\nchild.stdout.pipe(process.stdout);\nfor await (const line of createInterface({ input: process.stdin })) { const msg = JSON.parse(line); if (msg.method === 'session/new' || msg.method === 'session/load') writeFileSync(${JSON.stringify(configFile)}, JSON.stringify(msg.params.mcpServers)); child.stdin.write(line + '\\n'); }\nchild.stdin.end();\n`);
  const settingsFile = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsFile, "utf8"));
  settings.providerInstances.devReplay.config.commandArgs = [wrapper];
  await fs.writeFile(settingsFile, JSON.stringify(settings));
  const thread = await t3.thread({ project: group, title: "Tracked repository MCP proof", model: "question", messages: ["Check the tracked repositories."] });
  const servers = JSON.parse(await fs.readFile(configFile, "utf8"));
  const env = Object.fromEntries(servers.find((s: any) => s.name === "t3-code").env.map((e: any) => [e.name, e.value]));
  const mcp = client(env.T3_ACP_MCP_ENDPOINT, env.T3_ACP_MCP_AUTHORIZATION);
  await mcp.init();
  const read = decoded(await outside.call("t3_project_read", { projectId: project.id }));
  if (read.repositoryIdentity != null || read.trackedFolders.length !== 2) throw new Error(`Fixture does not match the multi-repository project: ${JSON.stringify(read)}`);
  const linked = await mcp.call("link_issue", { url: "https://github.com/pingdotgg/uploadthing/issues/1291" });
  const pr = await mcp.call("pull_request_read", { repository: "pingdotgg/uploadthing", number: 1 });
  await fs.writeFile(path.join(fixture, "mcp-results.json"), JSON.stringify({ linked, pr }, null, 2));
  const summary = `Actual MCP results (real GitHub; root has no remote, two tracked repositories):\n\nlink_issue uploadthing#1291:\n${text(linked)}\n\npull_request_read uploadthing#1:\n${text(pr)}`;
  await t3.open(thread);
  const stop = screen.getByRole("button", "Stop generation");
  await stop.waitFor({ timeout: 60000 });
  await stop.tap();
  await stop.waitFor({ state: "hidden" });
  await runPromise(cli(["thread", "send", thread.threadId, summary, "--wait", "--json"], [0, 2]));
  await stop.waitFor({ timeout: 60000 });
  await stop.tap();
  await stop.waitFor({ state: "hidden" });
  await screen.getByText("Actual MCP results", { exact: false }).first().waitFor({ timeout: 60000 });
  await screen.getByRole("button", /^Agent Actual MCP results/).tap();
  await screen.getByRole("status", "Syncing messages...").waitFor({ state: "hidden", timeout: 60000 });
  await app.screenshot("tracked-repository-mcp-results");
  await expect(Boolean(linked.isError || pr.isError)).toBe(false);
});
