import * as anthropic from "./anthropic.js";
import * as openai from "./openai.js";
import * as gemini from "./gemini.js";
import * as ollama from "./ollama.js";

const PROVIDERS = { anthropic, openai, gemini, ollama };
// Order matters for auto-detect when no AI_PROVIDER is set: cheapest paid
// providers first, Ollama last (Ollama is local-only, requires explicit opt-in
// or a reachable server).
const AUTO_ORDER = ["anthropic", "openai", "gemini", "ollama"];

export const ALL_PROVIDERS = AUTO_ORDER;

export function getProvider(nameRaw) {
  const key = String(nameRaw || "").toLowerCase();
  return PROVIDERS[key] || null;
}

export function getActiveProvider() {
  const requested = String(process.env.AI_PROVIDER || "").toLowerCase();
  if (requested) {
    const p = PROVIDERS[requested];
    if (p && p.isAvailable()) return p;
    return null;
  }
  for (const n of AUTO_ORDER) {
    if (PROVIDERS[n].isAvailable()) return PROVIDERS[n];
  }
  return null;
}

export function isAiAvailable() {
  return Boolean(getActiveProvider());
}

// Every provider whose key/config is present, in stable display order.
export function getConfiguredProviders() {
  return AUTO_ORDER
    .filter((n) => PROVIDERS[n].isAvailable())
    .map((n) => ({ name: n, model: PROVIDERS[n].activeModel() }));
}

export function getActiveProviderInfo() {
  const provider = getActiveProvider();
  const configured = getConfiguredProviders();
  if (!provider) {
    return {
      available: false,
      requested: process.env.AI_PROVIDER || null,
      configured,
      reason: process.env.AI_PROVIDER
        ? `AI_PROVIDER="${process.env.AI_PROVIDER}" is not configured (missing API key or unknown provider).`
        : "No AI provider configured. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, or use Ollama.",
    };
  }
  return {
    available: true,
    provider: provider.name,
    model: provider.activeModel(),
    configured,
  };
}

// `providerName` (optional): force this specific provider for this call,
// regardless of AI_PROVIDER. Must be one of the configured providers,
// otherwise throws.
export async function correctCity(args, providerName = null) {
  let provider;
  if (providerName) {
    const requested = String(providerName).toLowerCase();
    provider = PROVIDERS[requested];
    if (!provider) throw new Error(`Unknown AI provider: ${providerName}`);
    if (!provider.isAvailable()) throw new Error(`AI provider ${providerName} is not configured`);
  } else {
    provider = getActiveProvider();
    if (!provider) throw new Error("No AI provider configured");
  }
  return provider.correctCity(args);
}
