import { bufferSource, sha256Bytes, sha256Json, utf8 } from "./crypto";
import { ControlPlaneRun, ReceiptWitness, SyntheticReceiver } from "./durable";
import {
  bearer,
  errorResponse,
  json,
  requireCreationCapability,
  requireIdempotencyKey,
} from "./http";
import { deriveCapabilityToken, loadRoleSigners } from "./keys";
import { policyDigest } from "./policy";
import {
  PUBLIC_REQUEST_JSON_LIMITS,
  parseStrictJsonRequestWithBytes,
  requireClosedObject,
} from "./strict-json";
import {
  DEPLOYMENT_GATE,
  DISTRIBUTION,
  HttpError,
  LIMITATION,
  MATURITY,
  MCP_MEDIATED_VALUE,
  MCP_WIRE_PROTOCOL_REVISION,
  PROFILE,
  SERVICE_PROFILE,
  type Env,
  type JsonObject,
  type JsonValue,
} from "./types";
import manifestContract from "../fixtures/service-manifest-contract.json";
import { CAPABILITY_TOKEN_DERIVATION_VERSION } from "./constants";

export { ControlPlaneRun, ReceiptWitness, SyntheticReceiver };

const API_PREFIX = "/experimental/v1";
const MCP_VERSION = MCP_WIRE_PROTOCOL_REVISION;
const MCP_VERSION_META = "io.modelcontextprotocol/protocolVersion";
const BULLA_PERMIT_META = "io.glyphstandard/bullaPermit";
const CAPACITY_RUNS = 10_000;
const RUN_ID_PATTERN =
  /^run-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;

function allowedOrigins(env: Env): Set<string> {
  return new Set(env.ALLOWED_ORIGINS.split(",").map((value) => value.trim()).filter(Boolean));
}

function validateOrigin(request: Request, env: Env): string | null {
  const origin = request.headers.get("origin");
  if (origin === null) return null;
  if (!allowedOrigins(env).has(origin)) {
    throw new HttpError(403, "ORIGIN_NOT_ALLOWED", "request Origin is not accepted");
  }
  return origin;
}

function corsHeaders(origin: string | null): HeadersInit {
  return origin === null
    ? {}
    : {
        "access-control-allow-origin": origin,
        vary: "Origin",
      };
}

function withCors(response: Response, origin: string | null): Response {
  if (origin === null) return response;
  const headers = new Headers(response.headers);
  headers.set("access-control-allow-origin", origin);
  headers.append("vary", "Origin");
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
}

function requireJsonContentType(request: Request): void {
  const value = request.headers.get("content-type");
  if (value === null) {
    throw new HttpError(
      415,
      "UNSUPPORTED_MEDIA_TYPE",
      "Content-Type application/json is required",
    );
  }
  const segments = value.split(";").map((segment) => segment.trim());
  const valid =
    segments[0]?.toLowerCase() === "application/json" &&
    (segments.length === 1 ||
      (segments.length === 2 &&
        /^charset\s*=\s*(?:"utf-8"|utf-8)$/iu.test(segments[1] ?? "")));
  if (!valid) {
    throw new HttpError(
      415,
      "UNSUPPORTED_MEDIA_TYPE",
      "Content-Type application/json is required",
    );
  }
}

async function publicKeyFingerprint(jwk: JsonWebKey): Promise<string> {
  if (typeof jwk.x !== "string") throw new Error("Ed25519 public JWK has no x coordinate");
  const normalized = jwk.x.replaceAll("-", "+").replaceAll("_", "/");
  const bytes = Uint8Array.from(
    atob(`${normalized}${"=".repeat((4 - (normalized.length % 4)) % 4)}`),
    (character) => character.charCodeAt(0),
  );
  return sha256Bytes(bytes);
}

async function manifest(env: Env): Promise<JsonObject> {
  let roleIssuers: JsonObject | null = null;
  let witnessIssuer: string | null = null;
  let witnessFingerprint: string | null = null;
  if (env.KEY_PROVIDER_MODE === "PROVISIONED_JWK") {
    const signers = loadRoleSigners(env);
    roleIssuers = {
      evaluation_authority: signers.authorization.issuer,
      boundary: signers.boundary.issuer,
      target: signers.target.issuer,
      incident_commander: signers.incidentCommander.issuer,
      witness: signers.witness.issuer,
      publisher: signers.publication.issuer,
    };
    witnessIssuer = signers.witness.issuer;
    witnessFingerprint = await publicKeyFingerprint(signers.witness.publicJwk);
  }
  return {
    ...(manifestContract as unknown as JsonObject),
    deployment_gate: env.DEPLOYMENT_GATE,
    mcp_protocol_pin: env.MCP_PROTOCOL_PIN,
    policy_digest: await policyDigest(),
    witness_issuer: witnessIssuer,
    witness_public_key_sha256: witnessFingerprint,
    role_issuers: roleIssuers,
    trust_context_ref: env.TRUST_CONTEXT_REF,
    trust_context_sha256: env.TRUST_CONTEXT_SHA256,
    operational_gates: {
      key_rotation_retirement: env.KEY_ROTATION_RETIREMENT_GATE,
      retirement_export: env.RETIREMENT_EXPORT_GATE,
      transaction_reconciler: env.TRANSACTION_RECONCILER_GATE,
    },
    build: {
      commit: env.BUILD_COMMIT,
      version: env.CF_VERSION_METADATA.id,
    },
  };
}

function sourceKey(request: Request): string {
  return request.headers.get("cf-connecting-ip") ?? "originless-local-client";
}

async function rateLimit(request: Request, env: Env, kind: "create" | "mutate"): Promise<void> {
  const limiter = kind === "create" ? env.CREATE_RATE_LIMITER : env.MUTATE_RATE_LIMITER;
  const result = await limiter.limit({ key: sourceKey(request) });
  if (!result.success) throw new HttpError(429, "RATE_LIMITED", "request rate limit exceeded");
}

function runStub(env: Env, runId: string): DurableObjectStub {
  if (!RUN_ID_PATTERN.test(runId)) {
    throw new HttpError(404, "RUN_NOT_FOUND", "run identifier is malformed");
  }
  return env.CONTROL_PLANE_RUN.get(env.CONTROL_PLANE_RUN.idFromName(runId));
}

function witnessStub(env: Env): DurableObjectStub {
  return env.RECEIPT_WITNESS.get(env.RECEIPT_WITNESS.idFromName("receipt-witness"));
}

async function writeHeaders(request: Request, bodyBytes: Uint8Array): Promise<Headers> {
  const idempotencyKey = requireIdempotencyKey(request);
  const token = bearer(request);
  return new Headers({
    "content-type": "application/json",
    "x-idempotency-digest": await sha256Bytes(utf8(idempotencyKey)),
    "x-body-digest": await sha256Bytes(bodyBytes),
    "x-capability-digest": await sha256Bytes(utf8(token)),
  });
}

async function forwardWrite(
  request: Request,
  env: Env,
  runId: string,
  internalPath: string,
  body: JsonObject,
  bodyBytes: Uint8Array,
): Promise<Response> {
  return runStub(env, runId).fetch(`https://internal${internalPath}`, {
    method: "POST",
    headers: await writeHeaders(request, bodyBytes),
    body: JSON.stringify(body),
  });
}

async function replayMutation(
  request: Request,
  env: Env,
  runId: string,
  operation: "request" | "dispatch" | "direct" | "finalize",
  bodyBytes: Uint8Array,
): Promise<Response> {
  return runStub(env, runId).fetch(
    `https://internal/idempotency/replay/${operation}`,
    {
      method: "POST",
      headers: await writeHeaders(request, bodyBytes),
    },
  );
}

interface McpCall {
  id: JsonValue;
  method: "tools/list" | "tools/call";
  decisionAttestation: string | null;
  argumentsValue: JsonObject | null;
}

function headerMismatch(id: JsonValue, message: string): Response {
  return json(
    {
      jsonrpc: "2.0",
      id,
      error: { code: -32020, message: "HeaderMismatch", data: { detail: message } },
    },
    400,
  );
}

function acceptsMcpResponseTypes(value: string): boolean {
  const types = new Map<string, number>();
  for (const entry of value.split(",")) {
    const [rawType, ...rawParameters] = entry.split(";");
    const type = rawType?.trim().toLowerCase();
    if (
      type === undefined ||
      !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.test(type)
    ) {
      return false;
    }
    let quality = 1;
    let qualitySeen = false;
    for (const rawParameter of rawParameters) {
      const parameter = rawParameter.trim();
      const match =
        /^([a-z0-9!#$&^_.+-]+)\s*=\s*(?:"([\x20-\x7e]*)"|([a-z0-9!#$&^_.+-]+))$/iu.exec(
          parameter,
        );
      if (match === null) return false;
      if (match[1]?.toLowerCase() !== "q") continue;
      if (qualitySeen || match[2] !== undefined) return false;
      qualitySeen = true;
      const qualityText = match[3] ?? "";
      if (!/^(?:0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)$/u.test(qualityText)) {
        return false;
      }
      quality = Number(qualityText);
    }
    types.set(type, Math.max(types.get(type) ?? 0, quality));
  }
  return (types.get("application/json") ?? 0) > 0 &&
    (types.get("text/event-stream") ?? 0) > 0;
}

function jsonRpcError(
  id: JsonValue,
  code: -32600 | -32601 | -32602,
  message: "Invalid Request" | "Method not found" | "Invalid params",
  status: 400 | 404,
): Response {
  return json({ jsonrpc: "2.0", id, error: { code, message } }, status);
}

function validateMcp(request: Request, bodyValue: JsonValue, runId: string): McpCall | Response {
  let body: JsonObject;
  try {
    body = requireClosedObject(
      bodyValue,
      ["jsonrpc", "id", "method", "params"],
      ["jsonrpc", "id", "method"],
    );
  } catch {
    return jsonRpcError(null, -32600, "Invalid Request", 400);
  }
  const id = body.id ?? null;
  if (
    !(
      (typeof id === "string" &&
        id.length >= 1 &&
        id.length <= 128 &&
        /^[\x20-\x7e]+$/u.test(id)) ||
      (typeof id === "number" && Number.isSafeInteger(id))
    )
  ) {
    return jsonRpcError(null, -32600, "Invalid Request", 400);
  }
  if (body.jsonrpc !== "2.0" || typeof body.method !== "string") {
    return jsonRpcError(null, -32600, "Invalid Request", 400);
  }
  if (body.method !== "tools/list" && body.method !== "tools/call") {
    return jsonRpcError(id, -32601, "Method not found", 404);
  }
  const accept = request.headers.get("accept") ?? "";
  const protocolHeader = request.headers.get("mcp-protocol-version");
  const methodHeader = request.headers.get("mcp-method");
  const nameHeader = request.headers.get("mcp-name");
  let params: JsonObject;
  let metadata: JsonObject;
  try {
    params = requireClosedObject(
      body.params as JsonValue,
      body.method === "tools/list" ? ["_meta"] : ["name", "arguments", "_meta"],
      body.method === "tools/list" ? ["_meta"] : ["name", "arguments", "_meta"],
    );
    metadata = requireClosedObject(
      params._meta as JsonValue,
      body.method === "tools/list" ? [MCP_VERSION_META] : [MCP_VERSION_META, BULLA_PERMIT_META],
      body.method === "tools/list" ? [MCP_VERSION_META] : [MCP_VERSION_META, BULLA_PERMIT_META],
    );
  } catch {
    return jsonRpcError(id, -32602, "Invalid params", 400);
  }
  const expectedName = body.method === "tools/list" ? "tools/list" : params.name;
  if (
    !acceptsMcpResponseTypes(accept) ||
    protocolHeader !== MCP_VERSION ||
    metadata[MCP_VERSION_META] !== MCP_VERSION ||
    methodHeader !== body.method ||
    nameHeader !== expectedName
  ) {
    return headerMismatch(id, "MCP protocol, method, name, or Accept headers do not match the body");
  }
  if (body.method === "tools/list") {
    return {
      id,
      method: body.method,
      decisionAttestation: null,
      argumentsValue: null,
    };
  }
  if (params.name !== "sandbox.append") {
    return jsonRpcError(id, -32601, "Method not found", 404);
  }
  let argumentsValue: JsonObject;
  let permit: JsonObject;
  try {
    argumentsValue = requireClosedObject(
      params.arguments as JsonValue,
      ["value"],
      ["value"],
    );
    permit = requireClosedObject(
      metadata[BULLA_PERMIT_META] as JsonValue,
      ["run_id", "decision_attestation"],
      ["run_id", "decision_attestation"],
    );
  } catch {
    return jsonRpcError(id, -32602, "Invalid params", 400);
  }
  if (argumentsValue.value !== MCP_MEDIATED_VALUE) {
    return jsonRpcError(id, -32602, "Invalid params", 400);
  }
  if (
    permit.run_id !== runId ||
    typeof permit.decision_attestation !== "string" ||
    !/^sha256:[0-9a-f]{64}$/u.test(permit.decision_attestation)
  ) {
    return jsonRpcError(id, -32602, "Invalid params", 400);
  }
  return {
    id,
    method: body.method,
    decisionAttestation: permit.decision_attestation,
    argumentsValue,
  };
}

function synthesizedDispatchMcp(runId: string, decisionAttestation: string): {
  request: Request;
  body: JsonObject;
} {
  const body: JsonObject = {
    jsonrpc: "2.0",
    id: "dispatch-convenience",
    method: "tools/call",
    params: {
      name: "sandbox.append",
      arguments: { value: MCP_MEDIATED_VALUE },
      _meta: {
        [MCP_VERSION_META]: MCP_VERSION,
        [BULLA_PERMIT_META]: { run_id: runId, decision_attestation: decisionAttestation },
      },
    },
  };
  return {
    body,
    request: new Request("https://internal/mcp", {
      method: "POST",
      headers: {
        accept: "application/json, text/event-stream",
        "mcp-protocol-version": MCP_VERSION,
        "mcp-method": "tools/call",
        "mcp-name": "sandbox.append",
      },
    }),
  };
}

async function handleMcp(
  request: Request,
  env: Env,
  runId: string,
  body: JsonObject,
  bodyBytes: Uint8Array,
): Promise<Response> {
  const validated = validateMcp(request, body, runId);
  if (validated instanceof Response) return validated;
  if (validated.method === "tools/list") {
    return json({
      jsonrpc: "2.0",
      id: validated.id,
      result: {
        tools: [
          {
            name: "sandbox.append",
            description: `Append the fixed ${MCP_MEDIATED_VALUE} value to the synthetic receiver.`,
            inputSchema: {
              type: "object",
              properties: {
                value: { type: "string", const: MCP_MEDIATED_VALUE },
              },
              required: ["value"],
              additionalProperties: false,
            },
          },
        ],
      },
    });
  }
  const response = await forwardWrite(request, env, runId, "/dispatch", {
    decision_attestation: validated.decisionAttestation as string,
    arguments_hash: await sha256Json(validated.argumentsValue as JsonObject),
  }, bodyBytes);
  const payload = (await response.json()) as JsonValue;
  if (!response.ok) {
    const internalCode =
      payload !== null &&
      typeof payload === "object" &&
      !Array.isArray(payload) &&
      payload.error !== null &&
      typeof payload.error === "object" &&
      !Array.isArray(payload.error) &&
      typeof payload.error.code === "string"
        ? payload.error.code
        : null;
    const boundedCode =
      internalCode === "IDEMPOTENCY_CONFLICT"
        ? "IDEMPOTENCY_CONFLICT"
        : response.status === 400
        ? "INVALID_DISPATCH"
        : response.status === 401 || response.status === 403
          ? "AUTHORIZATION_REJECTED"
          : response.status === 409
            ? "PERMIT_REJECTED"
            : "DISPATCH_FAILED";
    return json(
      {
        jsonrpc: "2.0",
        id: validated.id,
        error: {
          code: -32030,
          message: "Tool execution failed",
          data: { code: boundedCode },
        },
      },
      response.status,
    );
  }
  return json({
    jsonrpc: "2.0",
    id: validated.id,
    result: {
      content: [{ type: "text", text: "fixed synthetic append delivered" }],
      structuredContent: payload,
      isError: false,
    },
  });
}

async function mcpExecutionResponse(
  validated: McpCall,
  response: Response,
): Promise<Response> {
  const payload = (await response.json()) as JsonValue;
  if (!response.ok) {
    const internalCode =
      payload !== null &&
      typeof payload === "object" &&
      !Array.isArray(payload) &&
      payload.error !== null &&
      typeof payload.error === "object" &&
      !Array.isArray(payload.error) &&
      typeof payload.error.code === "string"
        ? payload.error.code
        : null;
    const boundedCode =
      internalCode === "IDEMPOTENCY_CONFLICT"
        ? "IDEMPOTENCY_CONFLICT"
        : response.status === 400
        ? "INVALID_DISPATCH"
        : response.status === 401 || response.status === 403
          ? "AUTHORIZATION_REJECTED"
          : response.status === 409
            ? "PERMIT_REJECTED"
            : "DISPATCH_FAILED";
    return json(
      {
        jsonrpc: "2.0",
        id: validated.id,
        error: {
          code: -32030,
          message: "Tool execution failed",
          data: { code: boundedCode },
        },
      },
      response.status,
    );
  }
  return json({
    jsonrpc: "2.0",
    id: validated.id,
    result: {
      content: [{ type: "text", text: "fixed synthetic append delivered" }],
      structuredContent: payload,
      isError: false,
    },
  });
}

async function handle(request: Request, env: Env): Promise<Response> {
  const url = new URL(request.url);
  if (!url.pathname.startsWith(API_PREFIX)) throw new HttpError(404, "NOT_FOUND", "route not found");
  if (request.method === "OPTIONS") {
    const origin = validateOrigin(request, env);
    return new Response(null, {
      status: 204,
      headers: {
        ...corsHeaders(origin),
        "access-control-allow-methods": "GET, POST, OPTIONS",
        "access-control-allow-headers":
          "Authorization, Content-Type, Idempotency-Key, MCP-Protocol-Version, Mcp-Method, Mcp-Name",
        "access-control-max-age": "600",
      },
    });
  }
  const origin =
    request.method === "POST" ? validateOrigin(request, env) : request.headers.get("origin");
  if (origin !== null && !allowedOrigins(env).has(origin)) {
    throw new HttpError(403, "ORIGIN_NOT_ALLOWED", "request Origin is not accepted");
  }
  if (url.pathname === `${API_PREFIX}/manifest` && request.method === "GET") {
    return json(await manifest(env));
  }
  if (url.pathname === `${API_PREFIX}/runs` && request.method === "POST") {
    requireJsonContentType(request);
    const parsed = await parseStrictJsonRequestWithBytes(
      request,
      PUBLIC_REQUEST_JSON_LIMITS,
    );
    requireClosedObject(
      parsed.value,
      [],
      [],
    );
    const idempotencyKey = requireCreationCapability(request);
    const idempotencyDigest = await sha256Bytes(utf8(idempotencyKey));
    const bodyDigest = await sha256Bytes(parsed.bytes);
    const capabilityToken = await deriveCapabilityToken(env, idempotencyDigest);
    const capabilityHash = await sha256Bytes(utf8(capabilityToken));
    const allocationRequest = {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        idempotency_digest: idempotencyDigest,
        body_digest: bodyDigest,
        capability_key_version: CAPABILITY_TOKEN_DERIVATION_VERSION,
        capability_token_hash: capabilityHash,
      }),
    } satisfies RequestInit;
    let allocationResponse = await witnessStub(env).fetch(
      "https://internal/lookup-allocation",
      allocationRequest,
    );
    if (allocationResponse.status === 404) {
      await rateLimit(request, env, "create");
      allocationResponse = await witnessStub(env).fetch(
        "https://internal/allocate-run",
        allocationRequest,
      );
    }
    if (!allocationResponse.ok) return allocationResponse;
    const allocation = (await allocationResponse.json()) as { run_id: string };
    const initialization = await runStub(env, allocation.run_id).fetch("https://internal/initialize", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        run_id: allocation.run_id,
        capability_token_hash: capabilityHash,
      }),
    });
    if (!initialization.ok) return initialization;
    return json(
      { run_id: allocation.run_id, capability_token: capabilityToken, status: "CREATED" },
      201,
    );
  }
  let decodedPathname: string;
  try {
    decodedPathname = decodeURIComponent(url.pathname);
  } catch {
    throw new HttpError(400, "INVALID_PATH", "route path is not valid percent-encoding");
  }
  const witnessMatch = decodedPathname.match(
    new RegExp(
      `^${API_PREFIX}/witness/(checkpoints/latest|inclusion/(sha256:[0-9a-f]{64})|consistency|receipts/(sha256:[0-9a-f]{64}))$`,
      "u",
    ),
  );
  if (witnessMatch && request.method === "GET") {
    const suffix = witnessMatch[1] as string;
    return witnessStub(env).fetch(`https://internal/${suffix}${url.search}`);
  }
  const runMatch = url.pathname.match(
    new RegExp(
      `^${API_PREFIX}/runs/(run-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?:/(.*))?$`,
      "u",
    ),
  );
  if (!runMatch) throw new HttpError(404, "NOT_FOUND", "route not found");
  const runId = runMatch[1] as string;
  const suffix = runMatch[2] ?? "";
  if (request.method !== "GET" && request.method !== "POST") {
    throw new HttpError(405, "METHOD_NOT_ALLOWED", "method not allowed");
  }
  let body: JsonObject | null = null;
  let bodyBytes: Uint8Array | null = null;
  let mcpCall: McpCall | null = null;
  if (request.method === "POST") {
    requireJsonContentType(request);
    const parsed = await parseStrictJsonRequestWithBytes(
      request,
      PUBLIC_REQUEST_JSON_LIMITS,
    );
    bodyBytes = parsed.bytes;
    if (suffix === "mcp") {
      const validated = validateMcp(request, parsed.value, runId);
      if (validated instanceof Response) return validated;
      mcpCall = validated;
      body = parsed.value as JsonObject;
    } else {
      body = requireClosedObject(
        parsed.value,
        suffix === "requests"
          ? ["scenario"]
          : suffix === "dispatch"
            ? ["decision_attestation"]
            : [],
        suffix === "requests"
          ? ["scenario"]
          : suffix === "dispatch"
            ? ["decision_attestation"]
            : [],
      );
    }
  }
  const existenceResponse = await witnessStub(env).fetch(
    `https://internal/run-exists/${runId}`,
  );
  const existence = (await existenceResponse.json()) as { exists: boolean };
  if (!existence.exists) {
    if (request.method === "POST" && mcpCall?.method !== "tools/list") {
      await rateLimit(request, env, "mutate");
    }
    throw new HttpError(404, "RUN_NOT_FOUND", "run does not exist");
  }
  if (request.method === "GET") {
    if (suffix === "") return runStub(env, runId).fetch("https://internal/summary");
    if (suffix === "coverage") return runStub(env, runId).fetch("https://internal/coverage");
    if (suffix === "packet/manifest") {
      return runStub(env, runId).fetch("https://internal/packet/manifest");
    }
    if (suffix.startsWith("packet/")) {
      const path = suffix.slice("packet/".length);
      if (
        path.length === 0 ||
        path.includes("\\") ||
        path.startsWith("/") ||
        path.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
      ) {
        throw new HttpError(400, "UNSAFE_PACKET_PATH", "packet member path is unsafe");
      }
      const response = await runStub(env, runId).fetch(
        `https://internal/packet/member/${encodeURIComponent(path)}`,
      );
      if (url.searchParams.get("download") === "1" && response.ok) {
        const headers = new Headers(response.headers);
        headers.set("content-disposition", `attachment; filename="${path.split("/").at(-1)}"`);
        return new Response(response.body, { status: response.status, headers });
      }
      return response;
    }
    throw new HttpError(404, "NOT_FOUND", "run read route not found");
  }
  if (body === null || bodyBytes === null) throw new Error("run mutation body was not parsed");
  if (mcpCall?.method !== "tools/list") {
    const operation =
      suffix === "requests"
        ? "request"
        : suffix === "dispatch" || suffix === "mcp"
          ? "dispatch"
          : suffix === "test-only/direct-effect"
            ? "direct"
            : suffix === "finalize"
              ? "finalize"
              : null;
    if (operation !== null) {
      let replay: Response;
      try {
        replay = await replayMutation(request, env, runId, operation, bodyBytes);
      } catch (error) {
        await rateLimit(request, env, "mutate");
        throw error;
      }
      if (replay.status !== 404) {
        if (replay.status === 401 || replay.status === 403) {
          await rateLimit(request, env, "mutate");
        }
        if (suffix === "mcp" && mcpCall !== null) {
          return mcpExecutionResponse(mcpCall, replay);
        }
        return replay;
      }
    }
    await rateLimit(request, env, "mutate");
  }
  if (suffix === "requests") {
    return forwardWrite(request, env, runId, "/request", body, bodyBytes);
  }
  if (suffix === "dispatch") {
    if (
      typeof body.decision_attestation !== "string" ||
      !/^sha256:[0-9a-f]{64}$/u.test(body.decision_attestation)
    ) {
      throw new HttpError(400, "INVALID_DECISION", "decision_attestation is malformed");
    }
    const synthesized = synthesizedDispatchMcp(runId, body.decision_attestation);
    const validated = validateMcp(synthesized.request, synthesized.body, runId);
    if (validated instanceof Response || validated.decisionAttestation !== body.decision_attestation) {
      throw new HttpError(500, "MCP_DISPATCH_INVARIANT", "internal MCP dispatch validation failed");
    }
    return forwardWrite(request, env, runId, "/dispatch", {
      ...body,
      arguments_hash: await sha256Json(validated.argumentsValue as JsonObject),
    }, bodyBytes);
  }
  if (suffix === "test-only/direct-effect") {
    return forwardWrite(request, env, runId, "/direct", body, bodyBytes);
  }
  if (suffix === "finalize") {
    return forwardWrite(request, env, runId, "/finalize", body, bodyBytes);
  }
  if (suffix === "mcp") return handleMcp(request, env, runId, body, bodyBytes);
  throw new HttpError(404, "NOT_FOUND", "run mutation route not found");
}

const worker: ExportedHandler<Env> = {
  async fetch(request, env) {
    let origin: string | null = null;
    try {
      origin = request.headers.get("origin");
      return withCors(await handle(request, env), origin);
    } catch (error) {
      return withCors(errorResponse(error), origin !== null && allowedOrigins(env).has(origin) ? origin : null);
    }
  },
};

export default worker;
