/**
 * Anthropic 模型发现 Adapter。
 *
 * - 配置了 API Key：走 REST /v1/models；失败 throw，由 registry 不覆盖 DB。
 * - 未配置 Key：返回内置 seed 列表（CLI 认证场景由 registry 额外处理可用性）。
 */

import type { ModelRecord, ProviderAdapter, ProviderCredential, ConnectionTestResult } from '../types'
import { buildAnthropicRecord, fetchWithTimeout, bearerHeaders, normalizeBaseUrl } from './common'

const SEED_MODELS: ModelRecord[] = [
  buildAnthropicRecord('claude-sonnet-4-6', 'Claude Sonnet 4.6', 'Anthropic'),
  buildAnthropicRecord('claude-opus-4-6', 'Claude Opus 4.6', 'Anthropic'),
  buildAnthropicRecord('claude-haiku-4-5', 'Claude Haiku 4.5', 'Anthropic'),
]

interface AnthropicModelsResponse {
  data?: Array<{ id: string; display_name?: string }>
}

export class AnthropicAdapter implements ProviderAdapter {
  readonly providerId = 'anthropic'
  readonly defaultBaseUrl = 'https://api.anthropic.com'
  readonly authType = 'api_key' as const

  async listModels(credential: ProviderCredential): Promise<ModelRecord[]> {
    const baseUrl = normalizeBaseUrl(credential.baseUrl, this.defaultBaseUrl)
    // 没有 key 时无法调 REST，直接返回 seed（CLI 认证场景由 registry 额外处理可用性）
    if (!credential.apiKey) {
      return SEED_MODELS.map((m) => ({ ...m, source: 'seed' as const }))
    }

    const res = await fetchWithTimeout(`${baseUrl}/v1/models`, {
      headers: bearerHeaders(credential),
      timeoutMs: 15000,
    })
    if (!res.ok) {
      throw new Error(`Failed to list Anthropic models: HTTP ${res.status}`)
    }
    const json = (await res.json()) as AnthropicModelsResponse
    const data = json.data || []
    if (data.length === 0) {
      throw new Error('Anthropic returned an empty model list')
    }
    return data.map((m) =>
      buildAnthropicRecord(m.id, m.display_name || m.id, 'Anthropic'),
    ).map((m) => ({ ...m, source: 'dynamic' as const }))
  }

  async testConnection(credential: ProviderCredential): Promise<ConnectionTestResult> {
    const baseUrl = normalizeBaseUrl(credential.baseUrl, this.defaultBaseUrl)
    if (!credential.apiKey) {
      return { ok: false, error: 'No API key configured' }
    }
    try {
      const res = await fetchWithTimeout(`${baseUrl}/v1/messages`, {
        method: 'POST',
        headers: {
          ...bearerHeaders(credential),
          'anthropic-version': '2023-06-01',
        },
        body: JSON.stringify({
          model: 'claude-haiku-4-5-20251001',
          max_tokens: 1,
          messages: [{ role: 'user', content: 'hi' }],
        }),
        timeoutMs: 15000,
      })
      if (res.ok) return { ok: true }
      const data = await res.json().catch(() => ({})) as { error?: { message?: string } }
      return { ok: false, error: data.error?.message || `HTTP ${res.status}` }
    } catch (err) {
      return { ok: false, error: err instanceof Error ? err.message : 'Connection failed' }
    }
  }
}
