/**
 * API provider resolution for the Claude Agent SDK.
 *
 * 现在通过 model-registry 的持久化记录解析模型 → provider 映射，
 * 同时保留静态 MODEL_TO_PROVIDER 作为兜底。
 */

import { apiProviderRepo } from '@/lib/database/repositories/api-provider.repo'
import { providerModelRepo } from '@/lib/database/repositories/provider-model.repo'
import { getSetting } from '@/lib/settings-store'
import { PROVIDER_CATALOG } from '@/lib/engine/model-registry/catalog'
import { isClaudeCliAuthenticated } from '@/lib/claude-cli-auth'

export { isClaudeCliAuthenticated, getClaudeCliAccountInfo } from '@/lib/claude-cli-auth'

export interface ResolvedProvider {
  apiKey: string
  baseUrl?: string
  provider: string
  providerId: string
  /** True when using CLI OAuth instead of API key */
  isCliAuth: boolean
  /** Auth header type: 'api_key' for x-api-key, 'auth_token' for Bearer */
  authType: 'api_key' | 'auth_token'
}

import { MODEL_TO_PROVIDER } from './models'

function resolveDefaultModel(userId?: string): string {
  return getSetting('default_model', userId) || 'claude-sonnet-4-6'
}

function findProviderIdForModel(model: string, userId: string): string | undefined {
  // 优先从动态发现的模型记录中查找
  const stored = providerModelRepo.listByUser(userId).find((m) => m.modelId === model)
  if (stored) return stored.providerId
  // 兜底静态映射
  return MODEL_TO_PROVIDER[model]
}

/**
 * Resolve the API provider for a given model.
 * 优先使用 model-registry 中的动态记录，失败后回退到静态目录。
 */
export function resolveProvider(model?: string, userId?: string): ResolvedProvider {
  const effectiveModel = model || resolveDefaultModel(userId)
  const uid = userId || ''
  const providerId = findProviderIdForModel(effectiveModel, uid)

  // 1. Built-in provider
  if (providerId && !providerId.startsWith('custom-')) {
    const catalog = PROVIDER_CATALOG[providerId]
    if (!catalog) throw new Error(`Unknown provider for model: ${effectiveModel}`)

    const row = apiProviderRepo.findCredentialByProvider(providerId, uid)

    let baseUrl: string | undefined
    if (providerId === 'anthropic') {
      baseUrl = getSetting('custom_api_endpoint', userId) || row?.baseUrl || undefined
    } else {
      baseUrl = catalog.anthropicBaseUrl
    }

    if (row?.apiKey) {
      return {
        apiKey: row.apiKey,
        baseUrl,
        provider: row.provider || providerId,
        providerId: row.id || providerId,
        isCliAuth: false,
        authType: catalog.authType,
      }
    }

    if (providerId === 'anthropic' && isClaudeCliAuthenticated()) {
      return {
        apiKey: '',
        baseUrl,
        provider: 'anthropic',
        providerId: row?.id || providerId,
        isCliAuth: true,
        authType: 'api_key',
      }
    }

    if (providerId !== 'anthropic') {
      throw new Error(`No API key configured for ${providerId}. Please add your API key in Settings.`)
    }

    throw new Error('No Anthropic credentials found. Either add an API key in Settings, or run `claude login` in your terminal to authenticate with your Claude subscription.')
  }

  // 2. Custom provider
  if (providerId?.startsWith('custom-')) {
    const row = apiProviderRepo.findRawByIdAndUser(providerId, uid)
    if (!row) throw new Error(`Custom provider not found for model: ${effectiveModel}`)
    return {
      apiKey: row.apiKey,
      baseUrl: row.baseUrl || undefined,
      provider: 'custom',
      providerId,
      isCliAuth: false,
      authType: 'auth_token',
    }
  }

  // 3. Legacy custom provider lookup by model_name
  if (effectiveModel) {
    const customRow = apiProviderRepo.findCustomCredentialByModel(effectiveModel, uid)
    if (customRow) {
      return {
        apiKey: customRow.apiKey,
        baseUrl: customRow.baseUrl || undefined,
        provider: 'custom',
        providerId: customRow.id,
        isCliAuth: false,
        authType: 'auth_token',
      }
    }
  }

  // 4. Default to Anthropic
  const catalog = PROVIDER_CATALOG.anthropic
  const row = apiProviderRepo.findCredentialByProvider('anthropic', uid)

  if (row?.apiKey) {
    return {
      apiKey: row.apiKey,
      baseUrl: row.baseUrl || undefined,
      provider: 'anthropic',
      providerId: 'anthropic',
      isCliAuth: false,
      authType: catalog.authType,
    }
  }

  if (isClaudeCliAuthenticated()) {
    return {
      apiKey: '',
      baseUrl: undefined,
      provider: 'anthropic',
      providerId: 'anthropic',
      isCliAuth: true,
      authType: 'api_key',
    }
  }

  throw new Error('No Anthropic credentials found. Either add an API key in Settings, or run `claude login` in your terminal to authenticate with your Claude subscription.')
}

/**
 * Check if a provider has any credentials (API key or CLI auth).
 */
export function hasCredentials(providerId: string = 'anthropic'): boolean {
  const row = apiProviderRepo.findApiKeyById(providerId)
  if (row?.apiKey) return true
  if (providerId === 'anthropic') return isClaudeCliAuthenticated()
  return false
}

/**
 * Check if a provider has an API key configured (without throwing).
 */
export function hasApiKey(providerId: string = 'anthropic'): boolean {
  const row = apiProviderRepo.findApiKeyById(providerId)
  return !!row?.apiKey
}
