import { APICallError, RetryError } from "ai";
import type { ActiveAIProvider } from "./types";

export interface AIConfigurationErrorDetails {
  provider?: ActiveAIProvider | null;
  model?: string | null;
  missingFields?: string[];
  invalidFields?: string[];
}

export class AIConfigurationError extends Error {
  code: "providerMissing" | "invalidProvider" | "providerNotConfigured";
  details: AIConfigurationErrorDetails;

  constructor(
    code: "providerMissing" | "invalidProvider" | "providerNotConfigured",
    message: string,
    details: AIConfigurationErrorDetails = {}
  ) {
    super(message);
    this.name = "AIConfigurationError";
    this.code = code;
    this.details = details;
  }
}

export interface AIOutputTokenLimitErrorDetails {
  maxOutputTokens?: number;
  outputTokens?: number;
  reasoningTokens?: number;
}

/**
 * Thrown when a generation ends because the model hit the output token limit (finish reason
 * "length") before completing its response, so no valid structured output exists. Lives here so
 * apps can branch on a package-owned error with plain token counts instead of AI SDK internals.
 */
export class AIOutputTokenLimitError extends Error {
  details: AIOutputTokenLimitErrorDetails;

  constructor(details: AIOutputTokenLimitErrorDetails = {}) {
    super("AI generation stopped because the output token limit was reached");
    this.name = "AIOutputTokenLimitError";
    this.details = details;
  }
}

export type AIOAuthTokenErrorCode =
  /** The endpoint answered with a definitive non-2xx (a 4xx, or a 3xx since redirects are not followed). */
  | "token_request_failed"
  | "token_response_invalid"
  /** The endpoint answered 429. */
  | "token_endpoint_throttled"
  /** The endpoint answered 5xx. */
  | "token_endpoint_unavailable"
  | "token_endpoint_timeout"
  | "token_endpoint_unreachable";

/**
 * Fixed, status-neutral messages. An administrator reads these in the server log during an incident:
 * none may claim the credentials were rejected unless the code says so, or an identity-provider
 * outage sends them to rotate a secret that is fine.
 */
const OAUTH_TOKEN_ERROR_MESSAGES: Record<AIOAuthTokenErrorCode, string> = {
  token_request_failed: "OAuth2 token endpoint returned an error status for the token request",
  token_response_invalid: "OAuth2 token endpoint returned a response without a usable bearer token",
  token_endpoint_throttled: "OAuth2 token endpoint is rate-limiting token requests",
  token_endpoint_unavailable: "OAuth2 token endpoint returned a server error",
  token_endpoint_timeout: "OAuth2 token endpoint did not respond in time",
  token_endpoint_unreachable: "OAuth2 token endpoint could not be reached",
};

const TRANSIENT_OAUTH_TOKEN_ERROR_CODES: ReadonlySet<AIOAuthTokenErrorCode> = new Set([
  "token_endpoint_throttled",
  "token_endpoint_unavailable",
  "token_endpoint_timeout",
  "token_endpoint_unreachable",
]);

/**
 * Thrown when the OAuth2 client-credentials token for the AI provider cannot be obtained.
 *
 * This error is a secret-hygiene boundary: error reporters (PostHog's `serializeError` among them)
 * walk every own key and follow `cause`, redacting nothing. So it carries only enumerated,
 * non-secret scalars — a fixed message, a code, the HTTP status and the token endpoint's host —
 * and deliberately never sets `cause` or holds the response body, client id, secret or token.
 */
export class AIOAuthTokenError extends Error {
  readonly code: AIOAuthTokenErrorCode;
  readonly statusCode?: number;
  /** Host of the token endpoint only — no path or query, which some gateways use for tenant ids. */
  readonly tokenUrlHost: string;

  constructor(
    code: AIOAuthTokenErrorCode,
    { statusCode, tokenUrlHost }: { statusCode?: number; tokenUrlHost: string }
  ) {
    super(OAUTH_TOKEN_ERROR_MESSAGES[code]);
    this.name = "AIOAuthTokenError";
    this.code = code;
    this.statusCode = statusCode;
    this.tokenUrlHost = tokenUrlHost;
  }
}

export interface AIProviderErrorInfo {
  /** The provider (or its OAuth2 token endpoint) rejected this instance's credentials. */
  isAuthFailure: boolean;
  /** Provider returned HTTP 429 — quota / rate limit exhausted. */
  isQuotaExhausted: boolean;
  /** Whether the underlying call is worth retrying later. */
  isRetryable: boolean;
  statusCode?: number;
  /** Parsed from the provider's `retry-after` response header (seconds), when present. */
  retryAfterSeconds?: number;
}

const parseRetryAfterSeconds = (headers?: Record<string, string>): number | undefined => {
  const raw = headers?.["retry-after"];
  if (!raw) return undefined;
  // RFC 7231 allows either delay-seconds or an HTTP-date.
  const seconds = Number.parseInt(raw, 10);
  if (!Number.isNaN(seconds)) return seconds;
  const retryAt = new Date(raw);
  if (!Number.isNaN(retryAt.getTime())) {
    return Math.max(0, Math.ceil((retryAt.getTime() - Date.now()) / 1000));
  }
  return undefined;
};

const buildInfo = (error: APICallError): AIProviderErrorInfo => {
  const isQuotaExhausted = error.statusCode === 429;
  return {
    isAuthFailure: error.statusCode === 401 || error.statusCode === 403,
    isQuotaExhausted,
    // A 429 is always worth retrying later, even if the SDK didn't flag the call retryable.
    isRetryable: isQuotaExhausted || error.isRetryable,
    statusCode: error.statusCode,
    retryAfterSeconds: parseRetryAfterSeconds(error.responseHeaders),
  };
};

/**
 * Classify a thrown AI SDK error into provider-level signals the app can act on — chiefly whether
 * the provider returned a 429 (quota exhausted) so callers can surface a clear, retryable message
 * instead of a silent failure. Returns undefined for errors that aren't provider API/retry errors.
 *
 * Lives here so the `ai` SDK error types stay encapsulated in this package — apps consume the plain
 * `AIProviderErrorInfo` shape without importing the SDK directly.
 */
export const classifyAIProviderError = (error: unknown): AIProviderErrorInfo | undefined => {
  if (error instanceof AIOAuthTokenError) {
    // Only a definitive answer from the token endpoint is a credentials problem. A timeout, a network
    // failure or a 5xx is the identity provider being down, and a 429 is it throttling: reporting
    // either as "credentials rejected" would send an administrator to rotate a secret that is fine.
    // The 429 is surfaced as quota exhaustion so callers show their rate-limit message for it.
    const isThrottled = error.code === "token_endpoint_throttled";
    const isTransient = TRANSIENT_OAUTH_TOKEN_ERROR_CODES.has(error.code);
    return {
      isAuthFailure: !isTransient,
      isQuotaExhausted: isThrottled,
      isRetryable: isTransient,
      ...(error.statusCode === undefined ? {} : { statusCode: error.statusCode }),
    };
  }

  if (APICallError.isInstance(error)) {
    return buildInfo(error);
  }

  // After the SDK exhausts its internal retries it wraps the per-attempt errors in a RetryError;
  // dig out the most recent provider or token error to recover the real cause. The token error is
  // a candidate too: a retry after a gateway 5xx can fail at the token endpoint instead, and the
  // latest attempt is the one that describes the current state.
  if (RetryError.isInstance(error)) {
    const latest = [...error.errors, error.lastError]
      .reverse()
      .find(
        (candidate): candidate is APICallError | AIOAuthTokenError =>
          candidate instanceof AIOAuthTokenError || APICallError.isInstance(candidate)
      );
    if (latest instanceof AIOAuthTokenError) {
      return classifyAIProviderError(latest);
    }
    if (latest) {
      return buildInfo(latest);
    }
    return {
      isAuthFailure: false,
      isQuotaExhausted: false,
      isRetryable: error.reason === "maxRetriesExceeded",
    };
  }

  return undefined;
};
