import { readFile, readdir } from "node:fs/promises";
import { DatabaseSync } from "node:sqlite";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Use the credential actually issued to this scenario's replay process. No provider frames,
// orchestration records or task responses are synthesized by the driver.
async function agentAuthorization(threadId: string) {
  for (const pid of await readdir("/proc")) {
    if (!/^\d+$/.test(pid)) continue;
    const env = await readFile(`/proc/${pid}/environ`, "utf8").catch(() => "");
    const values = Object.fromEntries(env.split("\0").map((s) => {
      const at = s.indexOf("="); return [s.slice(0, at), s.slice(at + 1)];
    }));
    if (values.T3CODE_THREAD_ID === threadId && values.T3_ACP_MCP_AUTHORIZATION) {
      return values.T3_ACP_MCP_AUTHORIZATION;
    }
  }
  throw new Error("The scenario's live replay process has no MCP credential");
}

// The client projection omits unstarted cancelled runs. Read their persisted status without
// changing the destination database, so absence from a UI response cannot count as cancelled.
function persistedStatus(runId: string) {
  const db = new DatabaseSync(`${SECOND_HOME}/userdata/statev2.sqlite`, { readOnly: true });
  try { return db.prepare("SELECT status FROM orchestration_v2_projection_runs WHERE run_id = ?").get(runId)?.status; }
  finally { db.close(); }
}

async function mcp(origin: string, authorization: string) {
  let session: string | null = null;
  let id = 0;
  async function send(method: string, params?: object, notification = false) {
    const response = await fetch(`${origin}/mcp`, {
      method: "POST",
      headers: { authorization, "content-type": "application/json", accept: "application/json, text/event-stream", ...(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;
    const json = JSON.parse(body.startsWith("event:") || body.startsWith("data:") ? body.split("\n").find((line) => line.startsWith("data:"))!.slice(5) : body);
    if (json.error) throw new Error(JSON.stringify(json.error));
    return json.result;
  }
  await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "remote-cancellation-proof", version: "1" } });
  await send("notifications/initialized", {}, true);
  return async (name: string, args: object) => {
    const result = await send("tools/call", { name, arguments: args });
    if (result.isError) throw new Error(`${name}: ${JSON.stringify(result)}`);
    return result.structuredContent;
  };
}

test("Cancelling a queued remote follow-up leaves the active run alone and cannot be resumed", WEB, async ({ t3, app, browser, screen }) => {
  const origin = app.baseUrl!;
  const server = startSecondServer(origin);
  try {
    const { host, token } = await server.ready;
    const second = makeState(SECOND_HOME);
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      const remote = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, remote]) yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true, defaultRuntimeMode: "approval-required" } });
      const issued = yield* second.cli(["auth", "session", "issue", "--token-only"]);
      const response = yield* Effect.promise(() => fetch(`${host}/api/auth/pairing-token`, { method: "POST", headers: { authorization: `Bearer ${issued.stdout.trim()}`, "content-type": "application/json" }, body: JSON.stringify({ purpose: "peer-link", access: "full-access" }) }));
      const pairing = yield* Effect.promise(() => response.json());
      yield* primary["peerLinks.link"]({ url: host, pairingCode: pairing.credential, access: "full-access" });
    }).pipe(Effect.scoped));
    const project = await t3.project("Cancellation proof");
    const parent = await t3.thread({ project, title: "Originating task owner", messages: ["Keep the parent active"], model: "question" });
    const remoteProject = await second.state.project("Remote cancellation proof");
    await browser.setViewport({ width: 1440, height: 900 });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment", { exact: true }).tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment", { exact: true }).tap();
    await screen.getByRole("button", "Link from Scenario to Scenario: Full access, Reachable", { exact: true }).waitFor();

    console.log("PROOF: browser connected; acquiring live parent session");
    const call = await mcp(origin, await agentAuthorization(parent.threadId));
    const remoteEnv = await runPromise(environmentId(host));
    await call("orchestrator_capabilities", { environmentId: remoteEnv });
    const delegated = await call("delegate_task", { task: "Complete the initial remote task", title: "Remote follow-up cancellation", target: { environmentId: remoteEnv, projectId: (await call("t3_project_list", { environmentId: remoteEnv })).projects.find((p) => p.workspaceRoot === remoteProject).id, providerInstanceId: "devReplay", model: "multi-turn" }, mode: "wait", timeoutMs: 45000 });
    console.log("PROOF: initial delegation", JSON.stringify(delegated));
    const childId = delegated.remoteChild.threadId;
    if (delegated.status !== "completed") throw new Error(`Initial delegate did not complete: ${JSON.stringify(delegated)}`);
    await runPromise(Effect.gen(function* () {
      const remote = yield* rpcClient(SECOND_HOME, host);
      yield* remote["orchestration.dispatchCommand"]({ type: "thread.model-selection.set", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(childId), modelSelection: { instanceId: "devReplay", model: "question" } });
    }).pipe(Effect.scoped));
    console.log("PROOF: remote model set to question");
    const active = await call("t3_thread_send", { environmentId: remoteEnv, threadId: childId, message: "ACTIVE: keep this unrelated run waiting for my answer" });
    const queued = await call("t3_thread_send", { environmentId: remoteEnv, threadId: childId, message: "CANCEL ME: this queued follow-up must never start", mode: "queue" });
    if (active.delivery !== "started" || queued.delivery !== "queued" || !queued.taskId) throw new Error(`Follow-up setup failed: ${JSON.stringify({ active, queued })}`);
    console.log("PROOF: opening remote thread");
    await t3.open(`/${remoteEnv}/${childId}`);
    await screen.getByText("Should this fixture prefer strict schemas or UI flexibility?", { exact: true }).waitFor();
    await screen.getByRole("button", "Edit queued message").waitFor();
    await app.screenshot("before-cancellation");
    await call("task_cancel", { taskId: queued.taskId });
    // A read after the cancellation returns persisted state from the destination itself.
    const afterCancel = await runPromise(Effect.gen(function* () {
      const remote = yield* rpcClient(SECOND_HOME, host);
      return yield* remote["orchestration.getThreadProjection"]({ threadId: ThreadId.make(childId) });
    }).pipe(Effect.scoped));
    const cancelledBefore = persistedStatus(queued.runId);
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("after-cancellation");
    await runPromise(Effect.gen(function* () {
      const remote = yield* rpcClient(SECOND_HOME, host);
      yield* remote["orchestration.dispatchCommand"]({ type: "queue.resume", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(childId) });
    }).pipe(Effect.scoped));
    // Reopening reads the final destination state through the real client's connection.
    console.log("PROOF: opening remote thread");
    await t3.open(`/${remoteEnv}/${childId}`);
    await screen.getByText("ACTIVE: keep this unrelated run waiting for my answer", { exact: true }).waitFor();
    await screen.getByText("Should this fixture prefer strict schemas or UI flexibility?", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("after-queue-resume");
    const afterResume = await runPromise(Effect.gen(function* () {
      const remote = yield* rpcClient(SECOND_HOME, host);
      return yield* remote["orchestration.getThreadProjection"]({ threadId: ThreadId.make(childId) });
    }).pipe(Effect.scoped));
    const activeBefore = afterCancel.runs.find((run) => run.id === active.runId);
    
    const cancelledAfter = persistedStatus(queued.runId);
    console.log("REMOTE CANCELLATION RESULT", JSON.stringify({ activeAfterCancel: activeBefore?.status, queuedAfterCancel: cancelledBefore, queuedAfterResume: cancelledAfter }));
    expect({ activeInterrupted: activeBefore?.status === "interrupted", cancelledAfterCancel: cancelledBefore, cancelledAfterResume: cancelledAfter }).toEqual({ activeInterrupted: false, cancelledAfterCancel: "cancelled", cancelledAfterResume: "cancelled" });
  } finally { await server.stop(); }
});
