import type { ComboExclusion, ComboUnavailableDiagnostics } from "../../combos/resolve";
import { markProxyError } from "../../lib/client-error-body";
import { appendClientRetryIn, formatClientRetryAfter } from "../../lib/client-retry-after";
import { readBoundedResponseBody } from "../../lib/bounded-body";
import { redactSecretString } from "../../lib/redact";
import { isCyberPolicyMessage, isCyberPolicyCode } from "../../lib/errors";
import { isTranslatorBudgetExceededError } from "../../lib/translator-budget";
import { formatErrorResponse, formatUsageLimitReachedResponse } from "../../bridge";
import {
  UnsupportedContentEncodingError,
  DecompressedBodyTooLargeError,
  describeInboundBodyRefusal,
} from "../request-decompress";
import { comboCooldownRetryAfterSeconds, NoAvailableComboTargetsError } from "../../combos";
import type { AgentTaskRecoveryFailureReason } from "./agent-task-recovery";

/**
 * Materialize an upstream error body only when the bounded reader observed a complete,
 * display-safe payload. Partial timeout and over-limit prefixes are attacker-controlled,
 * so callers keep their existing status-only fallback instead.
 */
export async function readDisplaySafeErrorText(
  response: Response,
  signal: AbortSignal,
  fallback: string,
): Promise<string> {
  try {
    const body = await readBoundedResponseBody(response, { signal });
    return body.displaySafe ? body.text : fallback;
  } catch {
    // Preserve the former Response.text().catch(fallback) contract. Request-abort
    // classification remains owned by the surrounding response pipeline.
    return fallback;
  }
}


export interface NormalizedUpstreamErrorText {
  safeText: string;
  message?: string;
  type?: string;
  code?: string;
  cyberPolicy: boolean;
}


/**
 * Extract the structured provider error envelope without making `error.type` authoritative.
 * Policy identity comes from the dedicated code (or the legacy message fallback); a credible
 * upstream type is only carried through so callers do not erase provider diagnostics.
 */
export function normalizeUpstreamErrorText(text: string, fallback: string): NormalizedUpstreamErrorText {
  const safeText = redactSecretString(text).slice(0, 500).trim() || fallback;
  let message: string | undefined;
  let type: string | undefined;
  let code: string | undefined;
  try {
    const parsed = JSON.parse(text) as Record<string, unknown>;
    const response = parsed.response && typeof parsed.response === "object" && !Array.isArray(parsed.response)
      ? parsed.response as Record<string, unknown>
      : undefined;
    const candidates = [parsed.error, response?.error, response?.last_error, parsed.last_error, parsed];
    const source = candidates.find((candidate): candidate is Record<string, unknown> => {
      if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) return false;
      const record = candidate as Record<string, unknown>;
      return [record.message, record.type, record.code].some(value => typeof value === "string");
    });
    if (!source) return { safeText, cyberPolicy: isCyberPolicyMessage(safeText) };
    if (typeof source.message === "string" && source.message.trim()) {
      message = redactSecretString(source.message.trim()).slice(0, 500);
    }
    if (typeof source.type === "string" && source.type.trim()) type = source.type.trim();
    if (typeof source.code === "string" && source.code.trim()) {
      code = source.code.trim();
    }
  } catch {
    /* non-JSON upstream body — retain the bounded display-safe text */
  }
  const cyberPolicy = isCyberPolicyCode(code) || isCyberPolicyMessage(message ?? safeText);
  return { safeText, message, type, code, cyberPolicy };
}




export function decodeRequestErrorResponse(err: unknown, label: string): Response {
  if (isTranslatorBudgetExceededError(err)) {
    return markProxyError(formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", {
      code: "translation_buffer_limit",
    }));
  }
  if (err instanceof UnsupportedContentEncodingError) {
    return markProxyError(formatErrorResponse(415, "invalid_request_error", err.message));
  }
  if (err instanceof DecompressedBodyTooLargeError) {
    return markProxyError(formatErrorResponse(413, "inbound_body_too_large", describeInboundBodyRefusal(err)), "inbound");
  }
  console.warn(`[${label}] request body decode/parse failed: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`);
  return markProxyError(formatErrorResponse(400, "invalid_request_error", "Invalid JSON body"));
}




export function comboUnavailableResponse(
  message: string,
  options?: { retryAfter?: string | null; presentation?: "combo"; diagnostics?: ComboUnavailableDiagnostics },
): Response {
  const headers = new Headers({ "Content-Type": "application/json" });
  // Advice leaves in this proxy's format, whatever form the earliest cooldown was recorded in.
  const advice = formatClientRetryAfter(options?.retryAfter);
  if (advice !== undefined) headers.set("Retry-After", advice);
  // Name the earliest recovery in the body too: a client that drops the header still
  // shows the user how long the combo stays cooled.
  return markProxyError(new Response(
    JSON.stringify({
      // Built from the header value itself, so an HTTP-date cannot make the body and header disagree.
      // `combo` carries the machine-readable cause class and target counts (#7965).
      error: { message: appendClientRetryIn(message, advice), type: "server_error", code: "combo_unavailable",
        ...(options?.diagnostics ? { combo: options.diagnostics } : {}) },
    }),
    { status: 503, headers },
  ), options?.presentation);
}


export function comboUnavailable(comboId: string, now = Date.now(), exclusion?: ComboExclusion): Response {
  return comboUnavailableResponse(new NoAvailableComboTargetsError(comboId, exclusion).message, {
    retryAfter: comboCooldownRetryAfterSeconds(comboId, now),
    presentation: exclusion === undefined ? undefined : "combo",
    ...(exclusion ? { diagnostics: exclusion.diagnostics } : {}),
  });
}




/**
 * Build the 499 JSON error the proxy returns when the client disconnects before the
 * response completes (`client_cancelled`).
 */
export function clientCancelledResponse(): Response {
  return markProxyError(formatErrorResponse(499, "client_cancelled", "Client cancelled request"));
}

/**
 * The Responses answer to a local Anthropic pool refusal (`AnthropicAccountCooldownError`).
 *
 * When every held account is out on spent quota the refusal is a usage limit (#6991), which the
 * Codex client stops on and renders with its reset time; anything else stays the retryable
 * `rate_limit_error` it always was. A combo child keeps the retryable form and wording: the combo
 * hops on any 429 and rebuilds the body anyway, and `isAnthropicPoolLocalRefusal` in
 * `core-combo.ts` deliberately cools the target for the short local fallback, which a usage-limit
 * code or usage-limit prose would stretch to the ten-minute exhaustion fallback in
 * `combos/failover.ts`.
 */
export function anthropicPoolCooldownResponse(
  refusal: {
    message: string;
    retryableMessage: string;
    retryAfterSeconds: number | null;
    usageLimit: { readonly resetsAt: number | null } | null;
  },
  options: { comboAttempt?: boolean; logCtx?: { errorCode?: string } } = {},
): Response {
  if (refusal.usageLimit !== null && !options.comboAttempt) {
    if (options.logCtx) options.logCtx.errorCode = "usage_limit_reached";
    return markProxyError(formatUsageLimitReachedResponse(refusal.message, refusal.usageLimit.resetsAt, refusal.retryAfterSeconds), refusal.usageLimit.resetsAt === null ? undefined : "usage");
  }
  return markProxyError(formatErrorResponse(429, "rate_limit_error", refusal.retryableMessage,
    refusal.retryAfterSeconds === null ? undefined : { retryAfter: String(refusal.retryAfterSeconds) }));
}


export const UNREADABLE_ENCRYPTED_AGENT_TASK_MESSAGE =
  "Routed V2 worker task is encrypted for the native ChatGPT backend and cannot be read by the selected provider. Use plaintext V2 agent-message delivery or select a native ChatGPT model.";


export function unreadableEncryptedAgentTaskResponse(reason?: AgentTaskRecoveryFailureReason): Response {
  return markProxyError(new Response(
    JSON.stringify({
      error: {
        message: UNREADABLE_ENCRYPTED_AGENT_TASK_MESSAGE,
        type: "invalid_request_error",
        code: "unreadable_encrypted_agent_task",
        ...(reason === undefined ? {} : { recovery_reason: reason }),
      },
    }),
    { status: 400, headers: { "Content-Type": "application/json" } },
  ));
}


export const TARGET_INCOMPATIBLE_MESSAGE =
  "No remaining combo target can continue this tool-bearing history because the reasoning required for replay is unavailable after the serving route changed. Start a new conversation or configure a combo target that can consume the available reasoning.";


export function targetIncompatibleResponse(): Response {
  return markProxyError(new Response(
    JSON.stringify({
      error: {
        message: TARGET_INCOMPATIBLE_MESSAGE,
        type: "invalid_request_error",
        code: "target_incompatible",
      },
    }),
    { status: 400, headers: { "Content-Type": "application/json" } },
  ));
}
