import { codexWsIncrementalUploadEnabled } from "./codex-ws-incremental";
import {
  applyCodexRoutingHint,
  CODEX_RESPONSES_LITE_HEADER,
  CODEX_RESPONSES_LITE_METADATA_KEY,
} from "../../codex/forward-transport-headers";

/** Per-turn headers the WebSocket carries in `client_metadata` of each frame, not in the upgrade. */
export const CODEX_WS_FRAME_HEADERS = ["x-codex-turn-state", "x-codex-turn-metadata"] as const;

export const CODEX_RESPONSES_HTTP_URL = "https://chatgpt.com/backend-api/codex/responses";
export const CODEX_RESPONSES_WS_URL = "wss://chatgpt.com/backend-api/codex/responses";
export const WS_BETA = "responses_websockets=2026-02-06";

export interface PreparedCodexWsRequest {
  /** Fully synthesized frame; the transport measures this exact text before dialing. */
  frameText: string;
  headers: Record<string, string>;
  /** Original HTTP body/framing/options with only the canonical routing hint re-derived. */
  httpInit: RequestInit;
  canonical: boolean;
  /** The request's model id, when the body names one: a model the relayed metadata may report. */
  model?: string;
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function applyLiteMetadata(body: Record<string, unknown>, headers: Headers): boolean {
  const metadata = body.client_metadata;
  // Native client metadata is a string map. Do not spread malformed input or
  // turn boolean/number values into plausible but invented protocol strings.
  if (metadata !== undefined && (!isRecord(metadata)
    || Object.values(metadata).some(value => typeof value !== "string"))) return false;
  const lite = headers.get(CODEX_RESPONSES_LITE_HEADER);
  if (lite === "true" || lite === "false") {
    body.client_metadata = { ...(metadata as Record<string, string> | undefined),
      [CODEX_RESPONSES_LITE_METADATA_KEY]: lite };
  }
  for (const name of CODEX_WS_FRAME_HEADERS) {
    const value = headers.get(name);
    const current = body.client_metadata as Record<string, string> | undefined;
    if (value !== null && !Object.hasOwn(current ?? {}, name)) {
      body.client_metadata = { ...current, [name]: value };
    }
  }
  const requestId = headers.get("x-client-request-id");
  if (codexWsIncrementalUploadEnabled() && requestId !== null) {
    body.client_metadata = { ...(body.client_metadata as Record<string, string> | undefined), "x-client-request-id": requestId };
  }
  return true;
}

/** Pure preparation; null keeps malformed requests on the existing HTTP fallback path. */
export function prepareCodexHttpInit(url: string, init: RequestInit): RequestInit {
  if (url !== CODEX_RESPONSES_HTTP_URL || typeof init.body !== "string") return init;
  const headers = new Headers(init.headers);
  let body: unknown;
  try { body = JSON.parse(init.body); } catch { /* malformed body cannot authorize a hint */ }
  applyCodexRoutingHint(headers, body);
  return { ...init, headers };
}

/** Null refuses only WS conversion; canonical HTTP normalization is independently reusable. */
export function prepareCodexWsRequest(url: string, init: RequestInit): PreparedCodexWsRequest | null {
  if (typeof init.body !== "string") return null;
  try {
    const parsed: unknown = JSON.parse(init.body);
    if (!isRecord(parsed)) return null;
    const body = { ...parsed };
    const canonical = url === CODEX_RESPONSES_HTTP_URL;
    const httpHeaders = new Headers(init.headers);
    if (canonical) {
      if (!applyLiteMetadata(body, httpHeaders)) return null;
      applyCodexRoutingHint(httpHeaders, body);
    }
    const httpInit = { ...init, headers: httpHeaders };
    // WS is implicitly streaming; retain every other caller field except type.
    delete body.stream;
    const frameText = JSON.stringify({ ...body, type: "response.create" });
    const headers: Record<string, string> = {};
    httpHeaders.forEach((value, key) => {
      if (key === "content-type" || key === "content-length" || key === "accept" || key === "accept-encoding") return;
      headers[key] = value;
    });
    // Preserve the existing beta composition for both canonical and opted-in gateways.
    headers["openai-beta"] = headers["openai-beta"]
      ? headers["openai-beta"].includes("responses_websockets")
        ? headers["openai-beta"]
        : `${headers["openai-beta"]}, ${WS_BETA}`
      : WS_BETA;
    return { frameText, headers, httpInit, canonical, ...(typeof body.model === "string" ? { model: body.model } : {}) };
  } catch {
    return null;
  }
}
