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

export interface AudioFile {
  id: string
  filename: string
  file_path: string
  md5_hash: string
  file_size: number
  duration: number
  sample_rate: number
  channels: number
  format: string
  tempo?: number
  beat_times?: number[]
  spectral_centroid?: number
  spectral_rolloff?: number
  zero_crossing_rate?: number
  mfcc_features?: number[]
  frequency_chart_path?: string
  created_at: string
  updated_at: string
  is_active: boolean
}

export interface UploadAudioRequest {
  source_path: string
  filename?: string
}

export interface BatchUploadRequest {
  source_directory: string
}

export interface BatchUploadResult {
  total_files: number
  uploaded_files: number
  skipped_files: number
  failed_files: number
  uploaded_list: AudioFile[]
  skipped_list: Array<{ filename: string; reason: string }>
  failed_list: Array<{ filename: string; error: string }>
}

export interface ApiResponse<T> {
  status: boolean
  data?: T
  msg?: string
}

export class AudioService {
  /**
   * 尝试解析JSON响应
   */
  private static tryJsonParse(result: any): any {
    if (typeof result === 'string') {
      try {
        const parsed = JSON.parse(result)
        // 如果是JSON-RPC响应，提取result字段
        if (parsed.jsonrpc && 'result' in parsed) {
          return parsed.result
        }
        // 如果是普通JSON响应，直接返回
        return parsed
      } catch (error) {
        console.error('Failed to parse JSON:', error)
        return result
      }
    }
    return result
  }

  /**
   * 获取所有音频文件
   */
  static async getAllAudioFiles(): Promise<ApiResponse<AudioFile[]>> {
    try {
      const result = await invoke('get_all_audio_files')
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<AudioFile[]>
      }
      
      // 如果没有状态信息，假设成功并包装数据
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<AudioFile[]>
    } catch (error) {
      console.error('Failed to get all audio files:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 根据ID获取音频文件
   */
  static async getAudioById(audioId: string): Promise<ApiResponse<AudioFile>> {
    try {
      const result = await invoke('get_audio_by_id', { audioId })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<AudioFile>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<AudioFile>
    } catch (error) {
      console.error('Failed to get audio by id:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 根据MD5获取音频文件
   */
  static async getAudioByMd5(md5Hash: string): Promise<ApiResponse<AudioFile>> {
    try {
      const result = await invoke('get_audio_by_md5', { md5Hash })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<AudioFile>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<AudioFile>
    } catch (error) {
      console.error('Failed to get audio by md5:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 上传单个音频文件
   */
  static async uploadAudioFile(request: UploadAudioRequest): Promise<ApiResponse<AudioFile>> {
    try {
      const result = await invoke('upload_audio_file', { request })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<AudioFile>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<AudioFile>
    } catch (error) {
      console.error('Failed to upload audio file:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 批量上传音频文件
   */
  static async batchUploadAudioFiles(request: BatchUploadRequest): Promise<ApiResponse<BatchUploadResult>> {
    try {
      const result = await invoke('batch_upload_audio_files', { request })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<BatchUploadResult>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<BatchUploadResult>
    } catch (error) {
      console.error('Failed to batch upload audio files:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 删除音频文件
   */
  static async deleteAudioFile(audioId: string): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('delete_audio_file', { audioId })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<boolean>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<boolean>
    } catch (error) {
      console.error('Failed to delete audio file:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 搜索音频文件
   */
  static async searchAudioFiles(keyword: string): Promise<ApiResponse<AudioFile[]>> {
    try {
      const result = await invoke('search_audio_files', { keyword })
      const parsed = this.tryJsonParse(result)
      
      // 检查后端返回的实际状态
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<AudioFile[]>
      }
      
      // 如果没有状态信息，假设成功
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<AudioFile[]>
    } catch (error) {
      console.error('Failed to search audio files:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 格式化文件大小
   */
  static formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes'
    
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  /**
   * 格式化时长
   */
  static formatDuration(seconds: number): string {
    if (seconds === 0) return '0:00'
    
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }
}
