import { createHash, randomBytes } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A supervised MCP create retry preserves a task raised to full access", WEB, async ({ t3, app, screen }) => {
  await t3.project("Replay permission demo");
  const origin = app.baseUrl!;
  const cli = makeState(T3_HOME).cli;
  const owner = (await runPromise(cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
  const json = async (path: string, body: unknown, headers: Record<string,string> = {}) => {
    const response = await fetch(origin + path, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
    const data = await response.json();
    if (!response.ok) throw new Error(`${path}: ${JSON.stringify(data)}`);
    return data;
  };
  const projects = await (await fetch(origin + "/api/projects", { headers: { authorization: `Bearer ${owner}` } })).json();
  const projectId = projects.projects[0].id;
  const registered = await json("/oauth/mcp/register", { client_name: "Supervised replay proof", redirect_uris: ["http://127.0.0.1:54321/callback"] });
  const verifier = randomBytes(32).toString("base64url");
  const authorization = { response_type: "code", client_id: registered.client_id, redirect_uri: "http://127.0.0.1:54321/callback", code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256" };
  const pairing = JSON.parse((await runPromise(cli(["auth", "pairing", "create", "--json"]))).stdout);
  const approved = await json("/oauth/mcp/decision", { authorization, decision: { _tag: "pairing-code", access: "approval-required", code: pairing.credential } });
  const tokenResponse = await fetch(origin + "/oauth/mcp/token", { method: "POST", body: new URLSearchParams({ grant_type: "authorization_code", code: new URL(approved.redirectTo).searchParams.get("code")!, redirect_uri: authorization.redirect_uri, client_id: registered.client_id, code_verifier: verifier }) });
  const token = await tokenResponse.json();
  if (!token.access_token) throw new Error(`MCP authorization failed: ${JSON.stringify(token)}`);
  let session = "";
  let requestId = 0;
  const mcp = async (method: string, params: unknown) => {
    const response = await fetch(origin + "/mcp", { method: "POST", headers: { authorization: `Bearer ${token.access_token}`, "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": "2025-06-18", ...(session ? { "mcp-session-id": session } : {}) }, body: JSON.stringify({ jsonrpc: "2.0", id: ++requestId, method, params }) });
    session = response.headers.get("mcp-session-id") ?? session;
    const text = await response.text();
    const data = text.startsWith("{") ? JSON.parse(text) : text.split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6))).find(item => item.id === requestId);
    if (!response.ok || !data) throw new Error(`MCP ${method}: ${response.status} ${text}`);
    return data.result ?? data.error;
  };
  await mcp("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "replay-proof", version: "1" } });
  const call = (args: unknown) => mcp("tools/call", { name: "schedule_task", arguments: args });
  const request = { projectId, prompt: "Summarize the repo every morning", schedule: { type: "fixed_time", timeOfDay: "09:00" }, clientRequestId: "repro-key-1" };
  const created = await call(request);
  const readTask = () => runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    return Option.getOrThrow(yield* Stream.runHead(rpc["scheduledTasks.subscribe"]({}))).tasks[0]!;
  })));
  const initial = await readTask();
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    return yield* rpc["scheduledTasks.upsert"]({ ...initial, runtimeMode: "full-access" });
  })));
  const raised = await readTask();
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("switch", "Enable Summarize the repo every morning").waitFor();
  await app.screenshot("owner-raised-task");
  const control = await call({ scheduledTaskId: initial.id, enabled: false });
  const replay = await call({ ...request, enabled: false });
  const final = await readTask();
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("switch", "Enable Summarize the repo every morning").waitFor();
  await app.screenshot("after-supervised-retry");
  const safe = (task: typeof final) => ({ enabled: task.enabled, runtimeMode: task.runtimeMode, nextRunAt: task.nextRunAt, prompt: task.prompt, schedule: task.schedule });
  const transcript = { callerAccess: "approval-required", initial: safe(initial), raised: safe(raised), control, replay, final: safe(final) };
  // Keep only synthetic protocol responses; IDs are local synthetic identifiers.
  await writeFile(`${T3_HOME}/protocol-transcript.json`, JSON.stringify(transcript, null, 2));
  console.log("REPLAY_PROOF", JSON.stringify(transcript));
  await expect(replay.isError).toBe(true);
  await expect(final.runtimeMode).toBe("full-access");
  await expect(final.enabled).toBe(true);
});
