/**
 * DeepSeek 模型发现 Adapter。
 *
 * DeepSeek 支持 Anthropic-compatible 端点 https://api.deepseek.com/anthropic，
 * 模型发现优先尝试 OpenAI-compatible /models，全部失败则 throw（不写 seed 进 DB）。
 */

import type { ModelRecord, ProviderAdapter, ProviderCredential, ConnectionTestResult, ModelCapabilities } from '../types'
import { PROVIDER_CATALOG } from '../catalog'
import {
  buildGenericRecord,
  fetchWithTimeout,
  bearerHeaders,
  normalizeBaseUrl,
  parseOpenAIModelsResponse,
  testAnthropicCompatibleConnection,
} from './common'

const PROBE_MODEL = 'deepseek-v4-flash'

const defaultCapabilities = (): ModelCapabilities => ({
  contextWindow: 1_000_000,
  maxOutputTokens: 32_768,
  supportsVision: false,
  supportsThinking: true,
  supportsAdaptiveThinking: true,
  supportsEffort: false,
})

const deepseekCapabilities = (_id: string): ModelCapabilities => defaultCapabilities()

const SEED_MODELS: ModelRecord[] = [
  buildGenericRecord('deepseek-v4-flash', 'DeepSeek V4 Flash', 'deepseek', 'DeepSeek', defaultCapabilities()),
  buildGenericRecord('deepseek-v4-pro', 'DeepSeek V4 Pro', 'deepseek', 'DeepSeek', defaultCapabilities()),
]

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

  async listModels(credential: ProviderCredential): Promise<ModelRecord[]> {
    if (!credential.apiKey) return SEED_MODELS
    const baseUrl = normalizeBaseUrl(credential.baseUrl, this.defaultBaseUrl)
    // 优先尝试 OpenAI-compatible /models（DeepSeek 主站支持）
    const candidates = [
      baseUrl.replace(/\/anthropic$/, '') + '/models',
      `${baseUrl}/models`,
    ]
    let lastError = 'No reachable models endpoint'
    for (const url of candidates) {
      try {
        const res = await fetchWithTimeout(url, {
          headers: bearerHeaders(credential),
        })
        if (!res.ok) {
          lastError = `HTTP ${res.status} from ${url}`
          continue
        }
        const json = await res.json()
        const deprecated = new Set(['deepseek-chat', 'deepseek-reasoner'])
        const models = parseOpenAIModelsResponse(
          json as { data?: Array<{ id: string }> },
          'deepseek',
          'DeepSeek',
          deepseekCapabilities,
        ).filter((m) => !deprecated.has(m.id))
        if (models.length === 0) {
          lastError = 'DeepSeek returned an empty model list'
          continue
        }
        return models
      } catch (err) {
        lastError = err instanceof Error ? err.message : 'Request failed'
      }
    }
    throw new Error(`Failed to list DeepSeek models: ${lastError}`)
  }

  async testConnection(credential: ProviderCredential): Promise<ConnectionTestResult> {
    return testAnthropicCompatibleConnection({
      baseUrl: PROVIDER_CATALOG.deepseek.anthropicBaseUrl,
      apiKey: credential.apiKey,
      model: PROBE_MODEL,
    })
  }
}
