/**
 * LLM Router singleton for cowork-service.
 *
 * Provides multi-model LLM routing via @bytelyst/llm-router.
 * Supports cloud providers (Groq, OpenRouter, Together, Cerebras) and local Ollama.
 * Gated by the `llm_multi_model_enabled` feature flag.
 *
 * The Rust runtime still handles primary Anthropic calls — this router adds
 * alternative model access for multi-model comparison, fallback, and cost optimization.
 */

import { LlmRouter, createLocalOllamaProvider, type ProviderConfig, type TelemetryEntry } from '@bytelyst/llm-router';

let _router: LlmRouter | null = null;

export interface LlmRouterOptions {
  /** Additional providers beyond defaults. */
  extraProviders?: ProviderConfig[];
  /** Local Ollama model IDs (auto-creates local-ollama provider). */
  ollamaModels?: string[];
  /** Ollama base URL. Default: http://localhost:11434/v1 */
  ollamaBaseUrl?: string;
  /** Telemetry callback. */
  onTelemetry?: (entry: TelemetryEntry) => void;
}

/**
 * Initialize (or reinitialize) the LLM router singleton.
 * Call once during server startup.
 */
export function initLlmRouter(opts?: LlmRouterOptions): LlmRouter {
  const providers: ProviderConfig[] = [];

  // Add local Ollama if models are specified
  if (opts?.ollamaModels && opts.ollamaModels.length > 0) {
    providers.push(
      createLocalOllamaProvider(opts.ollamaModels, opts.ollamaBaseUrl),
    );
  }

  // Add any extra providers
  if (opts?.extraProviders) {
    providers.push(...opts.extraProviders);
  }

  // If no explicit providers, use defaults (cloud free-tier providers)
  const routerConfig = providers.length > 0 ? { providers } : undefined;

  // Use LlmRouter's built-in 30s timeout — appropriate for cloud LLM API calls.
  // (config.RUST_RUNTIME_TIMEOUT_MS is 300s and only for IPC, not HTTP.)
  _router = new LlmRouter({
    ...routerConfig,
    onTelemetry: opts?.onTelemetry,
  });

  return _router;
}

/**
 * Get the LLM router singleton. Throws if not initialized.
 */
export function getLlmRouter(): LlmRouter {
  if (!_router) {
    throw new Error('LLM router not initialized — call initLlmRouter() first');
  }
  return _router;
}

/**
 * Check if the LLM router has been initialized.
 */
export function isLlmRouterReady(): boolean {
  return _router !== null;
}

/** Reset singleton (for testing). */
export function resetLlmRouter(): void {
  _router = null;
}
