import { getProviderById } from '../config.js';
import { OpenAILLM } from './openai.js';
import { OllamaLLM } from './ollama.js';
import type { BaseLLM } from './base/llm.js';

function getEnvProvider(): { type: string; config: Record<string, unknown> } | null {
  const p = (process.env.LLM_PROVIDER ?? '').toLowerCase();
  if (p === 'ollama') {
    const baseURL =
      process.env.OLLAMA_BASE_URL ??
      (process.env.DOCKER ? 'http://host.docker.internal:11434' : 'http://localhost:11434');
    return { type: 'ollama', config: { baseURL } };
  }
  if (p === 'openai' || process.env.OPENAI_API_KEY) {
    return {
      type: 'openai',
      config: {
        apiKey: process.env.OPENAI_API_KEY ?? '',
        baseURL: process.env.OPENAI_BASE_URL ?? 'https://api.openai.com/v1',
      },
    };
  }
  return null;
}

export async function loadChatModel(providerId: string, modelKey: string): Promise<BaseLLM> {
  let provider = getProviderById(providerId);
  if (!provider) {
    const env = getEnvProvider();
    if (env) {
      provider = {
        id: 'env',
        name: env.type,
        type: env.type,
        chatModels: [{ key: modelKey, name: modelKey }],
        config: env.config,
      };
    }
  }
  if (!provider) throw new Error(`Provider not found: ${providerId}`);

  const hasModel = provider.chatModels?.some((m) => m.key === modelKey);
  if (!hasModel && provider.id !== 'env') {
    throw new Error(`Model ${modelKey} not found in provider ${providerId}`);
  }

  const cfg = provider.config as Record<string, unknown>;

  if (provider.type === 'openai') {
    const apiKey = (cfg.apiKey as string) || process.env.OPENAI_API_KEY;
    const baseURL = (cfg.baseURL as string) || 'https://api.openai.com/v1';
    if (!apiKey) throw new Error('OpenAI API key not configured');
    return new OpenAILLM({ apiKey, model: modelKey, baseURL });
  }

  if (provider.type === 'ollama') {
    const baseURL =
      (cfg.baseURL as string) ||
      process.env.OLLAMA_BASE_URL ||
      'http://localhost:11434';
    return new OllamaLLM({ baseURL, model: modelKey });
  }

  throw new Error(`Unsupported provider type: ${provider.type}`);
}
