import { env } from "cloudflare:workers";
import { backfillAccounts, backfillRepos } from "../backfill";
import { decryptSecret, encryptSecret } from "../crypto";
import { first } from "../db";
import { accountDb } from "../scoped-db";
import { badRequest, paymentRequired } from "../errors";
import { periodUsage } from "../metering/quota";
import { assertOutboundUrl } from "../integrations/outbound";
/**
* Bring-your-own AI. An endpoint is saved per account or per repository; the repository's wins. Every AI
* caller resolves its endpoint through resolveAiEndpoint, so precedence and validation live in one place.
* Keys are sealed with SECRETS_KEY and never returned once saved (summaries carry no key material).
*/
export const AI_ENDPOINT_KINDS = ["provider", "openai", "cf-gateway"] as const;
export type AiEndpointKind = (typeof AI_ENDPOINT_KINDS)[number];
export type AiScope = "account" | "repo";
export const BYOK_PROVIDERS = [
"openai",
"anthropic",
"google-ai-studio",
"groq",
"mistral",
"deepseek",
"cerebras",
"grok",
"openrouter",
"workers-ai",
] as const;
export type AiEndpointInput = {
kind: AiEndpointKind;
/** Provider slug for 'provider' and 'cf-gateway' (routed through Gateway's OpenAI-compatible endpoint). */
provider?: string | null;
model: string;
/** OpenAI-compatible base URL for 'openai', e.g. https://api.example.com/v1. */
baseUrl?: string | null;
cfAccountId?: string | null;
cfGatewayId?: string | null;