interface OpenRouterModel {
  id: string
  name: string
  description?: string
  context_length: number
  architecture: {
    modality: string
    tokenizer: string
    instruct_type?: string
  }
  pricing: {
    prompt: string
    completion: string
    request?: string
    image?: string
  }
  top_provider: {
    context_length: number
    max_completion_tokens?: number
    is_moderated: boolean
  }
  per_request_limits?: {
    prompt_tokens: string
    completion_tokens: string
  }
}

interface OpenRouterResponse {
  data: OpenRouterModel[]
}

export class OpenRouterService {
  private apiKey: string
  private baseUrl = 'https://openrouter.ai/api/v1'

  constructor() {
    this.apiKey = process.env.OPENROUTER_API_KEY || ''
    if (!this.apiKey) {
      throw new Error('OPENROUTER_API_KEY environment variable is required')
    }
  }

  async getAvailableModels(): Promise<OpenRouterModel[]> {
    try {
      const response = await fetch(`${this.baseUrl}/models`, {
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`OpenRouter API error: ${response.status} ${response.statusText}`)
      }

      const data: OpenRouterResponse = await response.json()
      return data.data || []
    } catch (error) {
      console.error('Error fetching OpenRouter models:', error)
      throw error
    }
  }

  // 将 OpenRouter 模型转换为我们数据库的格式
  transformModelForDB(model: OpenRouterModel) {
    return {
      modelId: model.id,
      name: model.name,
      provider: this.extractProvider(model.id),
      serviceProvider: 'openrouter',
      outputType: 'text',
      description: model.description || null,
      maxTokens: model.context_length || null,
      inputCostPer1k: parseFloat(model.pricing.prompt) * 1000 || null,
      outputCostPer1k: parseFloat(model.pricing.completion) * 1000 || null,
      supportedFeatures: {
        modality: model.architecture.modality,
        tokenizer: model.architecture.tokenizer,
        instruct_type: model.architecture.instruct_type,
        is_moderated: model.top_provider.is_moderated,
        max_completion_tokens: model.top_provider.max_completion_tokens,
      },
      metadata: {
        per_request_limits: model.per_request_limits,
        architecture: model.architecture,
        top_provider: model.top_provider,
      },
    }
  }

  private extractProvider(modelId: string): string {
    // 从模型 ID 中提取提供商名称，如 "openai/gpt-4" -> "OpenAI"
    const providerMap: Record<string, string> = {
      'openai': 'OpenAI',
      'anthropic': 'Anthropic',
      'google': 'Google',
      'meta-llama': 'Meta',
      'microsoft': 'Microsoft',
      'mistralai': 'Mistral AI',
      'cohere': 'Cohere',
    }

    const provider = modelId.split('/')[0] || 'Unknown'
    return providerMap[provider] || provider.charAt(0).toUpperCase() + provider.slice(1)
  }
}