interface UniAPIModel {
  id: string
  name: string
  description?: string
  provider?: string
  context_length?: number
  pricing?: {
    input: number
    output: number
  }
  features?: string[]
  type?: 'text' | 'image' | 'audio' | 'video' | 'multimodal'
}

interface UniAPIResponse {
  data: UniAPIModel[]
  error?: string
}

export class UniAPIService {
  private apiKey: string
  private baseUrl = 'https://api.uniapi.io/v1'

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

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

      if (!response.ok) {
        await response.text() // Read error text but don't use it
        throw new Error(`UniAPI error: ${response.status} ${response.statusText}`)
      }

      const data = await response.json()
      
      // 检查不同可能的响应格式
      let models: UniAPIModel[] = []
      
      if (data.data && Array.isArray(data.data)) {
        models = data.data
      } else if (Array.isArray(data)) {
        models = data
      } else if (data.models && Array.isArray(data.models)) {
        models = data.models
      } else {
        throw new Error('Unexpected response format from UniAPI')
      }

      if (data.error) {
        throw new Error(`UniAPI API error: ${data.error}`)
      }
      
      return models
    } catch (error) {
      console.error('Error fetching UniAPI models:', error)
      throw error
    }
  }

  // 将 UniAPI 模型转换为我们数据库的格式
  transformModelForDB(model: UniAPIModel) {
    // 确保模型有基本的属性
    if (!model.id) {
      return null
    }

    return {
      modelId: model.id,
      name: model.name || model.id || 'Unnamed Model', // 如果没有名称，使用模型ID作为后备
      provider: model.provider || this.extractProvider(model.id),
      serviceProvider: 'uniapi',
      outputType: model.type || 'text',
      description: model.description || null,
      maxTokens: model.context_length || null,
      inputCostPer1k: model.pricing?.input ? model.pricing.input * 1000 : null,
      outputCostPer1k: model.pricing?.output ? model.pricing.output * 1000 : null,
      supportedFeatures: {
        type: model.type,
        features: model.features || [],
      },
      metadata: {
        original: model,
      },
    }
  }

  private extractProvider(modelId: string): string {
    // 从模型 ID 中提取提供商名称
    const providerMap: Record<string, string> = {
      'openai': 'OpenAI',
      'anthropic': 'Anthropic', 
      'claude': 'Anthropic',
      'google': 'Google',
      'gemini': 'Google',
      'meta': 'Meta',
      'llama': 'Meta',
      'microsoft': 'Microsoft',
      'mistral': 'Mistral AI',
      'cohere': 'Cohere',
      'stability': 'Stability AI',
      'midjourney': 'Midjourney',
      'dall-e': 'OpenAI',
      'gpt': 'OpenAI',
    }

    const modelLower = modelId.toLowerCase()
    
    // 尝试从 ID 中匹配提供商
    for (const [key, value] of Object.entries(providerMap)) {
      if (modelLower.includes(key)) {
        return value
      }
    }

    // 如果包含斜杠，取斜杠前的部分
    if (modelId.includes('/')) {
      const provider = modelId.split('/')[0]
      return providerMap[provider.toLowerCase()] || 
             provider.charAt(0).toUpperCase() + provider.slice(1)
    }

    // 如果包含连字符，取第一个部分
    if (modelId.includes('-')) {
      const provider = modelId.split('-')[0]
      return providerMap[provider.toLowerCase()] || 
             provider.charAt(0).toUpperCase() + provider.slice(1)
    }

    return 'UniAPI'
  }

  // 执行聊天完成请求
  async createChatCompletion(params: {
    model: string
    messages: Array<{role: string, content: string}>
    temperature?: number
    max_tokens?: number
    top_p?: number
    frequency_penalty?: number
    presence_penalty?: number
  }) {
    try {
      const response = await fetch(`${this.baseUrl}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(`UniAPI API error: ${response.status} ${response.statusText} - ${errorData.error || ''}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Error calling UniAPI chat completion:', error)
      throw error
    }
  }

  // 执行图像生成请求
  async createImageGeneration(params: {
    model: string
    prompt: string
    size?: string
    quality?: string
    n?: number
  }) {
    try {
      const response = await fetch(`${this.baseUrl}/images/generations`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        throw new Error(`UniAPI API error: ${response.status} ${response.statusText} - ${errorData.error || ''}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Error calling UniAPI image generation:', error)
      throw error
    }
  }
}