import { createOpenAI } from "@ai-sdk/openai";
import { createAnthropic } from "@ai-sdk/anthropic";
import type { LanguageModel } from "ai";

export type AiProvider = "openai" | "anthropic" | "openrouter" | "ollama";

export type AiConfig = {
  provider?: AiProvider;
  model?: string;
  apiKey?: string;
  /** True when apiKey is the caller's own BYOK key — their own credentials
   * and billing, so platform AI-call quota shouldn't be charged for it. */
  isByok?: boolean;
};

export function resolveModel(config: AiConfig = {}): LanguageModel {
  const provider = config.provider ?? getDefaultProvider();

  switch (provider) {
    case "openai": {
      const openai = createOpenAI({ apiKey: config.apiKey ?? process.env["OPENAI_API_KEY"] });
      return openai(config.model ?? "gpt-4o-mini");
    }
    case "anthropic": {
      const anthropic = createAnthropic({ apiKey: config.apiKey ?? process.env["ANTHROPIC_API_KEY"] });
      return anthropic(config.model ?? "claude-haiku-4-5-20251001");
    }
    case "openrouter": {
      const openrouter = createOpenAI({
        apiKey: config.apiKey ?? process.env["OPENROUTER_API_KEY"],
        baseURL: "https://openrouter.ai/api/v1",
      });
      return openrouter(config.model ?? process.env["OPENROUTER_DEFAULT_MODEL"] ?? "google/gemini-flash-1.5");
    }
    case "ollama": {
      const ollama = createOpenAI({
        apiKey: "ollama",
        baseURL: process.env["OLLAMA_BASE_URL"] ?? "http://localhost:11434/v1",
      });
      return ollama(config.model ?? "llama3.2");
    }
    default: {
      throw new Error(`Unknown AI provider: ${String(provider)}`);
    }
  }
}

function getDefaultProvider(): AiProvider {
  if (process.env["OPENROUTER_API_KEY"]) return "openrouter";
  if (process.env["OPENAI_API_KEY"]) return "openai";
  if (process.env["ANTHROPIC_API_KEY"]) return "anthropic";
  return "ollama";
}
