import { invoke } from '@tauri-apps/api/tauri'

export interface Model {
  id: string
  model_number: string
  model_image: string
  is_active: boolean
  is_cloud: boolean
  user_id: string
  created_at: string
  updated_at: string
}

export interface ModelResponse {
  success: boolean
  data?: any
  error?: string
  message?: string
}

export interface ModelCreateRequest {
  model_number: string
  model_image: string
  user_id?: string
  is_cloud?: boolean
  verbose?: boolean
  json_output?: boolean
}

export interface ModelListRequest {
  user_id?: string
  include_cloud?: boolean
  include_inactive?: boolean
  limit?: number
  offset?: number
  verbose?: boolean
  json_output?: boolean
}

export interface ModelGetRequest {
  model_id: string
  verbose?: boolean
  json_output?: boolean
}

export interface ModelUpdateRequest {
  model_id: string
  model_number?: string
  model_image?: string
  is_active?: boolean
  is_cloud?: boolean
  verbose?: boolean
  json_output?: boolean
}

export interface ModelDeleteRequest {
  model_id: string
  hard_delete?: boolean
  verbose?: boolean
  json_output?: boolean
}

export interface ModelSearchRequest {
  query: string
  user_id?: string
  include_cloud?: boolean
  limit?: number
  verbose?: boolean
  json_output?: boolean
}

export class ModelServiceV2 {
  /**
   * 获取当前用户ID
   */
  private static getCurrentUserId(): string {
    // 这里应该从认证服务获取当前用户ID
    // 暂时返回默认值
    return 'default'
  }

  /**
   * 创建模特
   */
  static async createModel(
    modelNumber: string,
    modelImage: string,
    isCloud: boolean = false,
    userId?: string
  ): Promise<Model> {
    try {
      const request: ModelCreateRequest = {
        model_number: modelNumber,
        model_image: modelImage,
        user_id: userId || this.getCurrentUserId(),
        is_cloud: isCloud,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('create_model_cli', { request })
      
      if (!response.success) {
        throw new Error(response.error || response.message || 'Failed to create model')
      }

      return response.data?.model
    } catch (error) {
      console.error('Create model failed:', error)
      throw error
    }
  }

  /**
   * 获取模特列表
   */
  static async getAllModels(
    includeCloud: boolean = true,
    includeInactive: boolean = false,
    limit: number = 100,
    offset: number = 0,
    userId?: string
  ): Promise<{ models: Model[], total_count: number }> {
    try {
      const request: ModelListRequest = {
        user_id: userId || this.getCurrentUserId(),
        include_cloud: includeCloud,
        include_inactive: includeInactive,
        limit: limit,
        offset: offset,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('list_models_cli', { request })
      
      if (!response.success) {
        throw new Error(response.error || response.message || 'Failed to get models')
      }

      return {
        models: response.data?.models || [],
        total_count: response.data?.total_count || 0
      }
    } catch (error) {
      console.error('Get models failed:', error)
      throw error
    }
  }

  /**
   * 根据ID获取模特
   */
  static async getModelById(modelId: string): Promise<Model | null> {
    try {
      const request: ModelGetRequest = {
        model_id: modelId,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('get_model_cli', { request })
      
      if (!response.success) {
        if (response.error?.includes('不存在')) {
          return null
        }
        throw new Error(response.error || response.message || 'Failed to get model')
      }

      return response.data?.model || null
    } catch (error) {
      console.error('Get model failed:', error)
      throw error
    }
  }

  /**
   * 更新模特
   */
  static async updateModel(
    modelId: string,
    updates: {
      model_number?: string
      model_image?: string
      is_active?: boolean
      is_cloud?: boolean
    }
  ): Promise<boolean> {
    try {
      const request: ModelUpdateRequest = {
        model_id: modelId,
        ...updates,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('update_model_cli', { request })
      
      if (!response.success) {
        throw new Error(response.error || response.message || 'Failed to update model')
      }

      return true
    } catch (error) {
      console.error('Update model failed:', error)
      throw error
    }
  }

  /**
   * 删除模特
   */
  static async deleteModel(modelId: string, hardDelete: boolean = false): Promise<boolean> {
    try {
      const request: ModelDeleteRequest = {
        model_id: modelId,
        hard_delete: hardDelete,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('delete_model_cli', { request })
      
      if (!response.success) {
        throw new Error(response.error || response.message || 'Failed to delete model')
      }

      return true
    } catch (error) {
      console.error('Delete model failed:', error)
      throw error
    }
  }

  /**
   * 搜索模特
   */
  static async searchModels(
    query: string,
    includeCloud: boolean = true,
    limit: number = 50,
    userId?: string
  ): Promise<Model[]> {
    try {
      const request: ModelSearchRequest = {
        query: query,
        user_id: userId || this.getCurrentUserId(),
        include_cloud: includeCloud,
        limit: limit,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ModelResponse>('search_models_cli', { request })
      
      if (!response.success) {
        throw new Error(response.error || response.message || 'Failed to search models')
      }

      return response.data?.models || []
    } catch (error) {
      console.error('Search models failed:', error)
      throw error
    }
  }

  /**
   * 切换模特状态
   */
  static async toggleModelStatus(modelId: string): Promise<boolean> {
    try {
      // 先获取当前模特信息
      const model = await this.getModelById(modelId)
      if (!model) {
        throw new Error('模特不存在')
      }

      // 更新状态
      return await this.updateModel(modelId, {
        is_active: !model.is_active
      })
    } catch (error) {
      console.error('Toggle model status failed:', error)
      throw error
    }
  }

  /**
   * 获取模特数量统计
   */
  static async getModelStats(
    includeCloud: boolean = true,
    userId?: string
  ): Promise<{
    total: number
    active: number
    inactive: number
    cloud: number
    local: number
  }> {
    try {
      const { models } = await this.getAllModels(includeCloud, true, 1000, 0, userId)
      
      const stats = {
        total: models.length,
        active: models.filter(m => m.is_active).length,
        inactive: models.filter(m => !m.is_active).length,
        cloud: models.filter(m => m.is_cloud).length,
        local: models.filter(m => !m.is_cloud).length
      }

      return stats
    } catch (error) {
      console.error('Get model stats failed:', error)
      throw error
    }
  }

  /**
   * 批量删除模特
   */
  static async batchDeleteModels(
    modelIds: string[],
    hardDelete: boolean = false
  ): Promise<{ success: string[], failed: string[] }> {
    const results = {
      success: [] as string[],
      failed: [] as string[]
    }

    for (const modelId of modelIds) {
      try {
        await this.deleteModel(modelId, hardDelete)
        results.success.push(modelId)
      } catch (error) {
        console.error(`Failed to delete model ${modelId}:`, error)
        results.failed.push(modelId)
      }
    }

    return results
  }

  /**
   * 验证模特编号是否唯一
   */
  static async isModelNumberUnique(
    modelNumber: string,
    excludeId?: string,
    userId?: string
  ): Promise<boolean> {
    try {
      const models = await this.searchModels(modelNumber, true, 10, userId)
      
      // 检查是否有完全匹配的模特编号
      const exactMatch = models.find(m => 
        m.model_number === modelNumber && 
        m.id !== excludeId
      )
      
      return !exactMatch
    } catch (error) {
      console.error('Check model number uniqueness failed:', error)
      return false
    }
  }
}

export default ModelServiceV2
