import type { OcxProviderConfig } from "../types";
import { openaiResponsesUrl } from "../adapters/openai-responses-url";
import { isCanonicalOpenAiForwardProvider, normalizedBaseUrl } from "./openai-forward-destination";

export { CODEX_FORWARD_BASE_URL, isCanonicalOpenAiForwardProvider } from "./openai-forward-destination";

export const OPENAI_CODEX_PROVIDER_ID = "openai";
export const LEGACY_OPENAI_MULTI_PROVIDER_ID = "openai-multi";
export const OPENAI_API_PROVIDER_ID = "openai-apikey";
export const LEGACY_CHATGPT_PROVIDER_ID = "chatgpt";

/**
 * Response evidence is separate from Fast capability and request serialization. Preserve the
 * known Codex exception (#2558); other destinations may declare their response contract without
 * a gateway-name or URL heuristic. Absence retains the authoritative legacy default.
 */
export function responseTierAuthorityForProvider(provider: OcxProviderConfig): boolean | undefined {
  return isCanonicalOpenAiForwardProvider(provider) ? false : provider.responseTierAuthoritative;
}

const OPENAI_API_ORIGIN = "https://api.openai.com";
const OPENAI_API_BASE_URL = `${OPENAI_API_ORIGIN}/v1`;
const OPENAI_API_RESPONSES_URL = `${OPENAI_API_BASE_URL}/responses`;

/**
 * The Responses endpoint the adapter would actually POST key-auth traffic to, normalized.
 *
 * Mirrors the adapter's own construction (`src/adapters/openai-responses.ts`): a configured
 * `responsesPath` is appended to the base verbatim, and only the default branch runs the
 * `/v1/responses` suffix normalization. Classifying on the base URL alone would call
 * `baseUrl: "https://api.openai.com"` with `responsesPath: "/other"` official even though that
 * request never reaches the official Responses endpoint.
 */
function resolvedResponsesEndpoint(provider: OcxProviderConfig): string | undefined {
  try {
    const raw = provider.responsesPath === undefined
      ? openaiResponsesUrl(provider.baseUrl)
      : `${provider.baseUrl.replace(/\/$/, "")}${provider.responsesPath}`;
    return normalizedBaseUrl(raw);
  } catch {
    return undefined;
  }
}

function isOfficialOpenAiResponsesDestination(provider: OcxProviderConfig): boolean {
  // Exact normalized URL keeps lookalike/suffix hosts out of this set: `api.openai.com.evil.test`
  // resolves to its own origin, never to the official one.
  return resolvedResponsesEndpoint(provider) === OPENAI_API_RESPONSES_URL;
}

/**
 * Whether this provider can serve `POST /responses/compact`. The canonical ChatGPT
 * backend can, and so can the official OpenAI API — but an arbitrary gateway that
 * merely speaks the Responses wire cannot without an explicit capability opt-in (#422).
 * This is a protocol claim, not OpenAI identity or permission to forward caller credentials.
 */
export function supportsNativeResponsesCompactEndpoint(
  providerName: string,
  provider: OcxProviderConfig,
): boolean {
  if (isCanonicalOpenAiForwardProvider(provider)) return true;
  // Generic OAuth selection/refresh belongs to the routed Responses path, not this direct transport.
  if (provider.adapter === "openai-responses" && provider.supportsNativeCompactEndpoint === true
    && provider.authMode !== "oauth") return true;
  return providerName === OPENAI_API_PROVIDER_ID
    && provider.adapter === "openai-responses"
    && normalizedBaseUrl(provider.baseUrl) === OPENAI_API_BASE_URL;
}

/** Native v2 is independent of the v1 endpoint and ciphertext replay capabilities. */
export function supportsNativeResponsesCompactionTrigger(provider: OcxProviderConfig): boolean {
  return isCanonicalOpenAiForwardProvider(provider)
    || (provider.adapter === "openai-responses" && provider.supportsNativeCompactionTrigger === true);
}

/**
 * Whether this destination is an OpenAI-operated Responses backend — the canonical ChatGPT Codex
 * surface or the official OpenAI API.
 *
 * Deliberately not keyed on `authMode === "forward"`: a noncanonical forward provider does not
 * receive the caller's credentials (see the forward-header gate in the Responses adapter), so
 * forward auth says nothing about which backend is on the other end.
 */
export function isOpenAiOperatedResponsesDestination(provider: OcxProviderConfig): boolean {
  if (isCanonicalOpenAiForwardProvider(provider)) return true;
  return provider.adapter === "openai-responses"
    && isOfficialOpenAiResponsesDestination(provider);
}

/**
 * Whether this destination can decode a native (non-`ocx1:`) compaction blob.
 *
 * Only the backend that minted a blob can decode it. `authMode: "forward"` alone is not a signal:
 * the adapter forwards caller credentials only to the canonical ChatGPT Codex surface, while a
 * noncanonical forward provider receives no caller credentials and may point at any backend.
 *
 * Relay only to an OpenAI-operated destination or a destination whose operator explicitly opts in.
 * Keyed by destination rather than provider id: a blob's issuer is the URL that produced it, not the
 * local config key a replay travels under.
 */
export function destinationDecodesNativeCompactionBlob(provider: OcxProviderConfig): boolean {
  return isOpenAiOperatedResponsesDestination(provider)
    || provider.decodesNativeCompactionBlobs === true;
}
