import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { ChatAnthropic } from "@langchain/anthropic";
import { ChatOpenAI } from "@langchain/openai";

export type AiProvider = "google" | "claude" | "openai";

export function getLlm(provider: AiProvider, apiKey: string, model?: string) {
  if (provider === "claude") {
    return new ChatAnthropic({ model: model || "claude-haiku-4-5-20251001", apiKey });
  }
  if (provider === "openai") {
    return new ChatOpenAI({ model: model || "gpt-4o-mini", apiKey });
  }
  return new ChatGoogleGenerativeAI({ model: model || "gemini-1.5-flash", apiKey });
}

export interface AiSettingsLike {
  apiKey?: string | null;
  claudeAiKey?: string | null;
  claudeAiEnabled?: boolean | null;
  claudeAiModel?: string | null;
  openAiKey?: string | null;
  openAiEnabled?: boolean | null;
  openAiModel?: string | null;
  googleAiModel?: string | null;
}

export function resolveAiProvider(settings: AiSettingsLike): { provider: AiProvider; key: string; model: string } | null {
  if (settings.claudeAiEnabled && settings.claudeAiKey?.trim()) {
    return {
      provider: "claude",
      key: settings.claudeAiKey.trim(),
      model: settings.claudeAiModel?.trim() || "claude-haiku-4-5-20251001",
    };
  }
  if (settings.openAiEnabled && settings.openAiKey?.trim()) {
    return {
      provider: "openai",
      key: settings.openAiKey.trim(),
      model: settings.openAiModel?.trim() || "gpt-5.2",
    };
  }
  if (settings.apiKey?.trim()) {
    return {
      provider: "google",
      key: settings.apiKey.trim(),
      model: settings.googleAiModel?.trim() || "gemini-2.5-flash",
    };
  }
  return null;
}
