import { classifyNetworkFailure, type NetworkFailureCategory } from "./networkFailure.js";

export interface ProviderReadinessInput {
  readonly providerId: string;
  readonly baseUrl: string;
  readonly authToken: string;
  readonly anthropicApiKey: string;
}

export type ProviderReadinessProbe = (input: ProviderReadinessInput) => Promise<void>;

export class ProviderReadinessError extends Error {
  constructor(
    readonly code: "provider_readiness_unsupported" | "provider_readiness_unreachable" | "provider_readiness_rejected",
    message: string,
    readonly category: NetworkFailureCategory | "configuration" | "http",
    readonly upstreamStatus?: number,
  ) {
    super(message);
    this.name = "ProviderReadinessError";
  }
}

/** Verify the pilot's OpenRouter credential without starting or billing a model run. */
export async function probeOpenRouterCredential(input: ProviderReadinessInput): Promise<void> {
  if (input.providerId !== "openrouter") {
    throw new ProviderReadinessError(
      "provider_readiness_unsupported",
      `provider readiness probe is unavailable: ${input.providerId}`,
      "configuration",
    );
  }
  const base = input.baseUrl.endsWith("/") ? input.baseUrl : `${input.baseUrl}/`;
  const url = new URL("v1/key", base);
  const headers = new Headers({
    authorization: `Bearer ${input.authToken}`,
    accept: "application/json",
  });
  if (input.anthropicApiKey !== "") headers.set("x-api-key", input.anthropicApiKey);

  let response: Response;
  try {
    response = await fetch(url, {
      method: "GET",
      headers,
      redirect: "manual",
      signal: AbortSignal.timeout(10_000),
    });
  } catch (error) {
    throw new ProviderReadinessError(
      "provider_readiness_unreachable",
      "provider credential readiness check could not reach provider",
      classifyNetworkFailure(error),
    );
  }
  await response.body?.cancel();
  if (!response.ok) {
    throw new ProviderReadinessError(
      "provider_readiness_rejected",
      `provider credential readiness check failed: status ${response.status}`,
      "http",
      response.status,
    );
  }
}
