import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { execFileSync } from "node:child_process";
import { mkdirSync, readdirSync, readFileSync, writeFileSync, chmodSync, renameSync } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("link_issue refuses an unrelated project's tracker", WEB, async ({t3, app, browser, screen}) => {
  const unrelated = await t3.project("project-y");
  execFileSync("git", ["remote", "add", "origin", "https://github.com/octocat/Hello-World"], {cwd: unrelated});
  const project = await t3.project("project-x");
  renameSync(`${project}/.git`, `${project}/../project-x-git-metadata`);
  mkdirSync(`${project}/repo-a`);
  execFileSync("git", ["init", "--quiet"], {cwd: `${project}/repo-a`});
  execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/zact"], {cwd: `${project}/repo-a`});
  const thread = await t3.thread({project, title: "Issue link project ownership", model: "question", messages: ["first"]});
  const context = await runPromise(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    const {thread: shell} = yield* client["orchestration.getThreadProjection"]({threadId: thread.threadId});
    const snapshot = yield* client["orchestration.getArchivedShellSnapshot"]({});
    return {projectId: shell.projectId, projects: snapshot.projects.map(({id, title, repositoryIdentity}) => ({id, title, repositoryIdentity: repositoryIdentity ? {canonicalKey: repositoryIdentity.canonicalKey} : null}))};
  }).pipe(Effect.scoped));
  const {projectId} = context;
  const agentEnv = readdirSync("/proc").filter(p => /^\d+$/.test(p)).flatMap(pid => {
    try {
      const entries = Object.fromEntries(readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").map(e => {const at=e.indexOf("="); return [e.slice(0, at), e.slice(at+1)];}));
      return entries.T3CODE_THREAD_ID === thread.threadId && entries.T3_ACP_MCP_AUTHORIZATION ? [entries] : [];
    } catch { return []; }
  })[0];
  if (!agentEnv) throw new Error("The replay thread's MCP credential was not found");
  let session: string | null = null;
  let id = 0;
  async function send(method: string, params?: object, notification = false) {
    const response = await fetch(`${app.baseUrl}/mcp`, {method: "POST", headers: {
      "content-type": "application/json", accept: "application/json, text/event-stream", authorization: agentEnv.T3_ACP_MCP_AUTHORIZATION,
      ...(session ? {"mcp-session-id": session} : {})
    }, body: JSON.stringify({jsonrpc: "2.0", ...(notification ? {} : {id: ++id}), method, params})});
    session = response.headers.get("mcp-session-id") ?? session;
    const body = await response.text();
    if (!response.ok) throw new Error(`MCP ${response.status}: ${body}`);
    if (!body) return null;
    const json = body.startsWith("data:") || body.startsWith("event:") ? body.split("\n").filter(l=>l.startsWith("data: ")).map(l=>l.slice(6)).join("") : body;
    return JSON.parse(json).result;
  }
  await send("initialize", {protocolVersion: "2025-06-18", capabilities: {}, clientInfo: {name: "proof", version: "1"}});
  await send("notifications/initialized", {}, true);
  const call = (name: string, args: object) => send("tools/call", {name, arguments: args});
  const url = "https://github.com/pingdotgg/zact/issues/34";
  const implicit = await call("link_issue", {url});
  const unlinked = await call("unlink_issue", {url});
  const explicit = await call("link_issue", {url, projectId});
  const projectIssues = await call("list_issues", {projectId});
  const listed = await call("list_thread_issues", {});
  const result = {...context, implicit, unlinked, explicit, projectIssues, listed};
  console.log(JSON.stringify(result));
  if (process.env.PROOF_OUTPUT_DIR) writeFileSync(`${process.env.PROOF_OUTPUT_DIR}/mcp-${Date.now()}.json`, JSON.stringify(result, null, 2));
  const describe = (r: any) => r.isError ? r.content.map((c: any) => c.text).join(" ") : JSON.stringify(r.structuredContent);
  const linkedResult = (r: any) => r.isError ? describe(r) : `SUCCESS project=${context.projects.find(p => p.id === r.structuredContent.projectId)?.title} (${r.structuredContent.projectId}), scope=${r.structuredContent.scope}, key=${r.structuredContent.key}, alreadyLinked=${r.structuredContent.alreadyLinked}`;
  const report = [
    "REAL SERVER MCP RESULTS - issue #49695",
    `Thread project: project-x (${projectId})`,
    "URL: https://github.com/pingdotgg/zact/issues/34",
    "", "1. link_issue (default project):", linkedResult(implicit),
    "2. link_issue (explicit project-x, after unlink):", linkedResult(explicit),
    "3. list_issues (project-x):", describe(projectIssues),
    "4. list_thread_issues (persisted links):",
    listed.structuredContent.issues.length === 0 ? "issues: []" : listed.structuredContent.issues.map((i: any) => `project=${context.projects.find(p => p.id === i.projectId)?.title} (${i.projectId}), scope=${i.scope}, key=${i.key}, title=${i.title}`).join("\n"), "END OF SERVER RESULTS", ""
  ].join("\n");
  writeFileSync(`${project}/issue-link-result.txt`, report);
  writeFileSync(`${project}/show-results`, "#!/bin/sh\nprintf '\\033[2J\\033[H'\ncat issue-link-result.txt\nexec cat\n");
  chmodSync(`${project}/show-results`, 0o755);
  await runPromise(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["terminal.open"]({threadId: ThreadId.make(thread.threadId), terminalId: DEFAULT_TERMINAL_ID, cwd: project, env: {T3CODE_TERMINAL_SHELL: `${project}/show-results`}});
  }).pipe(Effect.scoped));
  await browser.setViewport({width: 1440, height: 1180});
  await t3.open(thread);
  await browser.evaluate(async ({threadId}) => {
    const {useTerminalUiStateStore} = await import(String("/src/terminalUiStateStore.ts"));
    const {environmentId} = await (await fetch("/.well-known/t3/environment")).json();
    useTerminalUiStateStore.getState().setTerminalHeight({environmentId, threadId}, 540);
  }, {threadId: thread.threadId});
  await screen.getByRole("button", "Toggle terminal drawer", {exact: true}).tap();
  await screen.getByLabel("Terminal input").waitFor();
  await app.screenshot("linked-issue-ownership");
  expect(JSON.stringify(implicit)).toContain("has no github.com issue tracker for pingdotgg/zact");
  expect(implicit?.isError, JSON.stringify({implicit, explicit, listed})).toBe(true);
  expect(explicit?.isError, JSON.stringify({explicit, listed})).toBe(true);
  expect(JSON.stringify(listed)).not.toContain('"key":"34"');
});
