/**
 * ProxyModel loader.
 * Loads built-in models and merges with local YAML definitions
 * from ~/.mcpctl/proxymodels/.
 */
import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { validateProxyModel, type ProxyModelDefinition } from './schema.js';
import { getBuiltInProxyModels } from './built-in-models.js';

const PROXYMODELS_DIR = join(process.env.HOME ?? '/tmp', '.mcpctl', 'proxymodels');

/**
 * Load all proxymodel definitions.
 * Built-ins are loaded first, then local YAML files override by name.
 */
export async function loadProxyModels(dir?: string): Promise<Map<string, ProxyModelDefinition>> {
  const models = getBuiltInProxyModels();

  // Load local YAML files (overrides built-ins)
  const localDir = dir ?? PROXYMODELS_DIR;
  try {
    const files = await readdir(localDir);
    for (const file of files) {
      if (!file.endsWith('.yaml') && !file.endsWith('.yml')) continue;
      try {
        const content = await readFile(join(localDir, file), 'utf-8');
        const raw = parseYaml(content) as unknown;
        const model = validateProxyModel(raw, 'local');
        models.set(model.metadata.name, model);
      } catch (err) {
        console.warn(`[proxymodel] Failed to load ${file}: ${(err as Error).message}`);
      }
    }
  } catch {
    // Directory doesn't exist or can't be read — use built-ins only
  }

  return models;
}

/**
 * Get a single proxymodel by name, or 'default' if not found.
 */
export async function getProxyModel(name: string, dir?: string): Promise<ProxyModelDefinition> {
  const models = await loadProxyModels(dir);
  const model = models.get(name);
  if (model) return model;

  // Fall back to default
  const defaultModel = models.get('default');
  if (defaultModel) return defaultModel;

  throw new Error(`ProxyModel '${name}' not found and no default model available`);
}
