/**
 * Moonshot (Kimi) 模型发现 Adapter。
 */

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

/** 连接探测用：与线上对话同一 Anthropic 路径，任选一个较新模型即可 */
const PROBE_MODEL = 'kimi-k2.6'

// 实测 api.moonshot.cn/anthropic 对 thinking 的 enabled/adaptive/disabled
// 三态均正确执行（kimi-k2.5/kimi-k2.6 均返回 thinking block，disabled 不返回）。
const defaultCapabilities = (): ModelCapabilities => ({
  contextWindow: 200_000,
  maxOutputTokens: 8192,
  supportsVision: true,
  supportsThinking: true,
  supportsAdaptiveThinking: true,
  supportsEffort: false,
})

const SEED_MODELS: ModelRecord[] = [
  buildGenericRecord('kimi-k2.6', 'Kimi K2.6', 'moonshot', 'Moonshot', defaultCapabilities()),
  buildGenericRecord('kimi-k2.5', 'Kimi K2.5', 'moonshot', 'Moonshot', defaultCapabilities()),
]

export class MoonshotAdapter implements ProviderAdapter {
  readonly providerId = 'moonshot'
  readonly defaultBaseUrl = 'https://api.moonshot.cn/v1'
  readonly authType = 'auth_token' as const

  async listModels(credential: ProviderCredential): Promise<ModelRecord[]> {
    const baseUrl = normalizeBaseUrl(credential.baseUrl, this.defaultBaseUrl)
    if (!credential.apiKey) return SEED_MODELS

    const res = await fetchWithTimeout(`${baseUrl}/models`, {
      headers: bearerHeaders(credential),
    })
    if (!res.ok) {
      throw new Error(`Failed to list Moonshot models: HTTP ${res.status}`)
    }
    const json = await res.json()
    const models = parseOpenAIModelsResponse(
      json as { data?: Array<{ id: string }> },
      'moonshot',
      'Moonshot',
      defaultCapabilities,
    )
    if (models.length === 0) {
      throw new Error('Moonshot returned an empty model list')
    }
    return models
  }

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