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

test("A supervised schedule retry preserves a task raised to full access", WEB, async ({ t3, app, screen }) => {
  await t3.project("Scheduled replay demo");
  const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const post = async (path: string, body: unknown) => {
    const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
    const result = await response.json();
    if (!response.ok) throw new Error(`HTTP ${response.status}: ${JSON.stringify(result)}`);
    return result;
  };
  const redirect = "http://localhost:51234/callback";
  const registered = await post("/oauth/mcp/register", { client_name: "Replay proof supervised client", redirect_uris: [redirect], grant_types: ["authorization_code", "refresh_token"], token_endpoint_auth_method: "none" });
  const verifier = "proof-verifier-abcdefghijklmnopqrstuvwxyz0123456789";
  const authorization = { response_type: "code", client_id: registered.client_id, redirect_uri: redirect, code_challenge: createHash("sha256").update(verifier).digest("base64url"), code_challenge_method: "S256", state: "proof", resource: `${origin}/mcp` };
  const pairing = JSON.parse((await runPromise(makeState(T3_HOME).cli(["auth", "pairing", "create", "--json"]))).stdout);
  const decision = await post("/oauth/mcp/decision", { authorization, decision: { _tag: "pairing-code", access: "approval-required", code: pairing.credential } });
  const code = new URL(decision.redirectTo).searchParams.get("code")!;
  const tokenResponse = await fetch(`${origin}/oauth/mcp/token`, { method: "POST", body: new URLSearchParams({ grant_type: "authorization_code", code, client_id: registered.client_id, redirect_uri: redirect, code_verifier: verifier, resource: `${origin}/mcp` }) });
  const token = await tokenResponse.json();
  if (!token.access_token) throw new Error("OAuth token exchange failed");
  let session = "";
  let id = 0;
  const mcp = async (method: string, params: unknown) => {
    const response = await fetch(`${origin}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token.access_token}`, accept: "application/json, text/event-stream", "content-type": "application/json", ...(session ? { "mcp-session-id": session, "mcp-protocol-version": "2025-06-18" } : {}) }, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }) });
    session = response.headers.get("mcp-session-id") ?? session;
    const text = await response.text();
    const parsed = text.startsWith("event:") || text.startsWith("data:") ? JSON.parse(text.split("\n").find((line) => line.startsWith("data: "))!.slice(6)) : JSON.parse(text);
    if (parsed.error) throw new Error(JSON.stringify(parsed.error));
    return parsed.result;
  };
  await mcp("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "replay-proof", version: "1" } });
  const call = (name: string, args: unknown) => mcp("tools/call", { name, arguments: args });
  const unpack = (result: any) => result.structuredContent ?? JSON.parse(result.content.find((item: any) => item.type === "text").text);
  const projects = unpack(await call("t3_project_list", {}));
  const projectId = projects.projects[0].id;
  const input = { projectId, prompt: "Summarize the repo every morning", schedule: { type: "fixed_time", timeOfDay: "09:00" }, clientRequestId: "repro-key-1" };
  const created = unpack(await call("schedule_task", input));
  const saved = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    const listed = yield* client["scheduledTasks.subscribe"]({}).pipe(Stream.take(1), Stream.runHead);
    if (listed._tag !== "Some") throw new Error("No task listing");
    const task = listed.value.tasks[0];
    return yield* client["scheduledTasks.upsert"]({ ...task, runtimeMode: "full-access" });
  }).pipe(Effect.scoped));
  const control = await call("schedule_task", { scheduledTaskId: saved.task.id, enabled: false });
  if (!control.isError || !JSON.stringify(control).includes("runtime_mode_escalation_denied")) throw new Error(`Control did not refuse: ${JSON.stringify(control)}`);
  const replay = await call("schedule_task", { ...input, enabled: false });
  const final = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    const listed = yield* client["scheduledTasks.subscribe"]({}).pipe(Stream.take(1), Stream.runHead);
    if (listed._tag !== "Some") throw new Error("No final listing");
    return listed.value.tasks[0];
  }).pipe(Effect.scoped));
  const transcript = { created, authorizedSave: { enabled: saved.task.enabled, runtimeMode: saved.task.runtimeMode }, control, replay, final: { enabled: final.enabled, runtimeMode: final.runtimeMode, nextRunAt: final.nextRunAt } };
  console.log("REPLAY_PROOF", JSON.stringify(transcript));
  await writeFile(`${T3_HOME}/replay-proof.json`, JSON.stringify(transcript, null, 2));
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("switch", "Enable Summarize the repo every morning").waitFor({ state: "visible" });
  await app.screenshot("scheduled-task-after-supervised-retry");
  await expect(screen.getByRole("switch", "Enable Summarize the repo every morning")).toBeChecked();
  expect(replay.isError).toBe(true);
  expect(final.runtimeMode).toBe("full-access");
});
