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

export interface VideoSegment {
  id: string
  original_video_id: string
  segment_index: number
  filename: string
  file_path: string
  md5_hash: string
  file_size: number
  duration: number
  width: number
  height: number
  fps: number
  format: string
  start_time: number
  end_time: number
  tags: string[]
  use_count: number
  thumbnail_path?: string
  scene_score?: number
  motion_score?: number
  brightness?: number
  contrast?: number
  created_at: string
  updated_at: string
  is_active: boolean
}

export interface OriginalVideo {
  id: string
  filename: string
  file_path: string
  md5_hash: string
  file_size: number
  duration: number
  width: number
  height: number
  fps: number
  format: string
  segment_count: number
  tags: string[]
  created_at: string
  updated_at: string
  is_active: boolean
}

export interface UploadVideoRequest {
  source_path: string
  filename?: string
  tags?: string[]
}

export interface BatchUploadVideoRequest {
  source_directory: string
  tags?: string[]
}

export interface TagsRequest {
  segment_id: string
  tags: string[]
}

export interface SearchTagsRequest {
  tags: string[]
  match_all?: boolean
}

export interface UploadVideoResult {
  original_video: OriginalVideo
  segments: VideoSegment[]
  is_duplicate: boolean
}

export interface BatchUploadResult {
  total_files: number
  uploaded_files: number
  skipped_files: number
  failed_files: number
  total_segments: number
  uploaded_list: UploadVideoResult[]
  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 MediaService {
  /**
   * 尝试解析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 getAllSegments(): Promise<ApiResponse<VideoSegment[]>> {
    try {
      const result = await invoke('get_all_segments')
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<VideoSegment[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<VideoSegment[]>
    } catch (error) {
      console.error('Failed to get all segments:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 获取所有原始视频
   */
  static async getAllOriginalVideos(): Promise<ApiResponse<OriginalVideo[]>> {
    try {
      const result = await invoke('get_all_original_videos')
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<OriginalVideo[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<OriginalVideo[]>
    } catch (error) {
      console.error('Failed to get all original videos:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 根据视频ID获取片段
   */
  static async getSegmentsByVideoId(videoId: string): Promise<ApiResponse<VideoSegment[]>> {
    try {
      const result = await invoke('get_segments_by_video_id', { videoId })
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<VideoSegment[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<VideoSegment[]>
    } catch (error) {
      console.error('Failed to get segments by video id:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 上传单个视频文件
   */
  static async uploadVideoFile(request: UploadVideoRequest): Promise<ApiResponse<UploadVideoResult>> {
    try {
      const result = await invoke('upload_video_file', { request })
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<UploadVideoResult>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<UploadVideoResult>
    } catch (error) {
      console.error('Failed to upload video file:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 批量上传视频文件
   */
  static async batchUploadVideoFiles(request: BatchUploadVideoRequest): Promise<ApiResponse<BatchUploadResult>> {
    try {
      const result = await invoke('batch_upload_video_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 video files:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 添加片段标签
   */
  static async addSegmentTags(request: TagsRequest): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('add_segment_tags', { request })
      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 add segment tags:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 移除片段标签
   */
  static async removeSegmentTags(request: TagsRequest): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('remove_segment_tags', { request })
      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 remove segment tags:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 增加片段使用次数
   */
  static async incrementSegmentUsage(segmentId: string): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('increment_segment_usage', { segmentId })
      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 increment segment usage:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 根据标签搜索片段
   */
  static async getSegmentsByTags(request: SearchTagsRequest): Promise<ApiResponse<VideoSegment[]>> {
    try {
      const result = await invoke('get_segments_by_tags', { request })
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<VideoSegment[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<VideoSegment[]>
    } catch (error) {
      console.error('Failed to get segments by tags:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 获取热门片段
   */
  static async getPopularSegments(limit?: number): Promise<ApiResponse<VideoSegment[]>> {
    try {
      const result = await invoke('get_popular_segments', { limit })
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<VideoSegment[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<VideoSegment[]>
    } catch (error) {
      console.error('Failed to get popular segments:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 搜索片段
   */
  static async searchSegments(keyword: string): Promise<ApiResponse<VideoSegment[]>> {
    try {
      const result = await invoke('search_segments', { keyword })
      const parsed = this.tryJsonParse(result)
      
      if (parsed && typeof parsed === 'object' && 'status' in parsed) {
        return parsed as ApiResponse<VideoSegment[]>
      }
      
      return { status: true, msg: 'ok', data: parsed } as ApiResponse<VideoSegment[]>
    } catch (error) {
      console.error('Failed to search segments:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 删除片段
   */
  static async deleteSegment(segmentId: string): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('delete_segment', { segmentId })
      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 segment:', error)
      return {
        status: false,
        msg: error instanceof Error ? error.message : 'Unknown error'
      }
    }
  }

  /**
   * 删除原始视频
   */
  static async deleteOriginalVideo(videoId: string): Promise<ApiResponse<boolean>> {
    try {
      const result = await invoke('delete_original_video', { videoId })
      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 original video:', 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')}`
  }

  /**
   * 格式化分辨率
   */
  static formatResolution(width: number, height: number): string {
    return `${width}×${height}`
  }
}
