'use strict';

const { sanitizeSetupProviderType } = require('./setup-provider-config');

function _kv(brain, key) {
  try {
    if (brain && typeof brain.getKv === 'function') return brain.getKv(key) || '';
    if (brain && typeof brain.getDb === 'function') {
      return brain.getDb().prepare('SELECT value FROM brain_metadata WHERE key = ?').get(key)?.value || '';
    }
  } catch (e) {
    if (process.env.CTM_DEBUG_WALLE_DEFAULTS === '1') {
      console.warn('[walle-default-model] metadata lookup failed:', e.message);
    }
  }
  return '';
}

function _providerDefault(provider, providerRegistry) {
  if (!provider) return '';
  try {
    const registry = providerRegistry || require('../../wall-e/llm/registry');
    if (typeof registry.ensureBootstrapped === 'function') registry.ensureBootstrapped();
    return registry.getDefaultModel(provider) || '';
  } catch (e) {
    if (process.env.CTM_DEBUG_WALLE_DEFAULTS === '1') {
      console.warn('[walle-default-model] provider default lookup failed:', e.message);
    }
    return '';
  }
}

function resolveWalleDefaultModelSelection(opts = {}) {
  const env = opts.env || process.env;
  const brain = opts.brain || null;
  const provider = sanitizeSetupProviderType(
    _kv(brain, 'walle_provider')
      || env.WALLE_PROVIDER
      || 'anthropic'
  ) || 'anthropic';
  const model = _kv(brain, 'walle_model_' + provider)
    || _kv(brain, 'walle_model')
    || env.WALLE_MODEL
    || _providerDefault(provider, opts.providerRegistry)
    || '';

  return {
    model_id: model,
    model_provider: provider,
  };
}

module.exports = {
  resolveWalleDefaultModelSelection,
};
