import { LLMProvider } from '../plugins/plugin_entry.js';
import { AnthropicProvider } from '../plugins/llm_providers/anthropic.js';
import { OpenAIProvider } from '../plugins/llm_providers/openai.js';
import { DeepSeekProvider } from '../plugins/llm_providers/deepseek.js';

const providers: Map<string, LLMProvider> = new Map();

export function registerProvider(provider: LLMProvider): void {
  providers.set(provider.id, provider);
}

export function getProvider(id: string): LLMProvider {
  const p = providers.get(id);
  if (!p) throw new Error(`LLM 提供商 "${id}" 未注册`);
  return p;
}

let _initialized = false;
export function initDefaultProviders(): void {
  if (_initialized) return;
  _initialized = true;
  registerProvider(new AnthropicProvider());
  registerProvider(new OpenAIProvider());
  registerProvider(new DeepSeekProvider());
}

export interface ModelRef {
  provider: string;
  model: string;
}

export function parseModelRef(modelStr: string): ModelRef {
  // 格式: "provider:model" 或 "model"（默认 openai）
  const parts = modelStr.split(':');
  if (parts.length === 2) return { provider: parts[0], model: parts[1] };
  // 根据模型名推断提供商
  if (modelStr.startsWith('claude')) return { provider: 'anthropic', model: modelStr };
  if (modelStr.startsWith('deepseek')) return { provider: 'deepseek', model: modelStr };
  return { provider: 'openai', model: modelStr };
}
