'use strict';

function normalizeModelId(providerId, modelId) {
  const provider = String(providerId || '').trim().toLowerCase();
  const model = String(modelId || '').trim();
  if (!model) return '';
  if (model.includes('/')) return model;
  return provider ? `${provider}/${model}` : model;
}

function buildModelCatalog(manifests = []) {
  const models = new Map();
  const aliases = new Map();
  for (const manifest of manifests || []) {
    if (manifest.kind !== 'provider') continue;
    const providerId = manifest.id;
    for (const item of manifest.modelCatalog || []) {
      const normalizedId = normalizeModelId(providerId, item.id || item.model);
      if (!normalizedId) continue;
      const record = {
        id: normalizedId,
        providerId,
        model: normalizedId.split('/').slice(1).join('/'),
        displayName: item.displayName || item.name || normalizedId,
        contextWindow: item.contextWindow || item.context_window || null,
        inputCostPer1M: item.inputCostPer1M ?? item.input_cost_per_1m ?? null,
        outputCostPer1M: item.outputCostPer1M ?? item.output_cost_per_1m ?? null,
        capabilities: { ...(item.capabilities || {}) },
      };
      models.set(normalizedId, record);
      for (const alias of item.aliases || []) aliases.set(String(alias), normalizedId);
    }
    for (const prefix of manifest.modelPrefixes || []) aliases.set(prefix, `${providerId}/${prefix}*`);
  }
  return {
    list: () => [...models.values()],
    resolve: (id) => {
      const raw = String(id || '');
      if (models.has(raw)) return models.get(raw);
      if (aliases.has(raw) && models.has(aliases.get(raw))) return models.get(aliases.get(raw));
      for (const [alias, target] of aliases.entries()) {
        if (target.endsWith('*') && raw.startsWith(alias)) {
          return { id: normalizeModelId(target.slice(0, target.indexOf('/')), raw), providerId: target.slice(0, target.indexOf('/')), model: raw, inferred: true };
        }
      }
      return null;
    },
    aliases: () => new Map(aliases),
  };
}

module.exports = {
  buildModelCatalog,
  normalizeModelId,
};
