/**
 * 素材导入服务
 * 处理素材导入、模特选择和自动分镜功能
 */

import { invoke } from '@tauri-apps/api/core'
import { VideoSegment } from './mediaService'
import { Model } from './modelService'

export interface ImportMaterialConfig {
  // 基础配置
  projectId: string
  sourceDirectory: string
  selectedModelIds: string[]
  
  // 导入选项
  includeSubdirectories: boolean
  fileTypes: string[] // 支持的文件类型
  
  // 自动分镜配置
  enableAutoSegmentation: boolean
  segmentationConfig: {
    method: 'scene' | 'time' | 'smart' // 分镜方法
    sceneThreshold: number // 场景变化阈值 (0-1)
    timeInterval: number // 时间间隔分镜（秒）
    minSegmentDuration: number // 最小片段时长（秒）
    maxSegmentDuration: number // 最大片段时长（秒）
  }
  
  // 处理选项
  generateThumbnails: boolean
  extractMetadata: boolean
  autoTagging: boolean
}

export interface ImportProgress {
  stage: 'scanning' | 'importing' | 'segmenting' | 'processing' | 'completed' | 'error'
  progress: number // 0-100
  message: string
  currentFile?: string
  processedFiles: number
  totalFiles: number
  segmentedVideos: number
  generatedSegments: number
}

export interface ImportResult {
  success: boolean
  message: string
  importedMaterials: VideoSegment[]
  generatedSegments: VideoSegment[]
  skippedFiles: string[]
  errors: string[]
  statistics: {
    totalFiles: number
    importedFiles: number
    segmentedVideos: number
    totalSegments: number
    processingTime: number
  }
}

export interface FileInfo {
  path: string
  name: string
  size: number
  type: string
  duration?: number
  resolution?: string
  isSupported: boolean
}

export class MaterialImportService {
  /**
   * 获取默认导入配置
   */
  static getDefaultConfig(projectId: string): ImportMaterialConfig {
    return {
      projectId,
      sourceDirectory: '',
      selectedModelIds: [],
      includeSubdirectories: true,
      fileTypes: ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', 'm4v'],
      enableAutoSegmentation: true,
      segmentationConfig: {
        method: 'smart',
        sceneThreshold: 0.3,
        timeInterval: 30,
        minSegmentDuration: 3,
        maxSegmentDuration: 60
      },
      generateThumbnails: true,
      extractMetadata: true,
      autoTagging: true
    }
  }

  /**
   * 扫描目录获取可导入的文件
   */
  static async scanDirectory(directoryPath: string, config: ImportMaterialConfig): Promise<FileInfo[]> {
    try {
      const result = await invoke('scan_import_directory', {
        directoryPath,
        includeSubdirectories: config.includeSubdirectories,
        fileTypes: config.fileTypes
      })
      
      return result as FileInfo[]
    } catch (error) {
      console.error('Failed to scan directory:', error)
      throw new Error(`扫描目录失败: ${error}`)
    }
  }

  /**
   * 开始导入素材
   */
  static async startImport(config: ImportMaterialConfig): Promise<{ taskId: string }> {
    try {
      const result = await invoke('start_material_import', { config })
      return result as { taskId: string }
    } catch (error) {
      console.error('Failed to start import:', error)
      throw new Error(`开始导入失败: ${error}`)
    }
  }

  /**
   * 获取导入进度
   */
  static async getImportProgress(taskId: string): Promise<ImportProgress> {
    try {
      const result = await invoke('get_import_progress', { taskId })
      return result as ImportProgress
    } catch (error) {
      console.error('Failed to get import progress:', error)
      throw new Error(`获取导入进度失败: ${error}`)
    }
  }

  /**
   * 取消导入任务
   */
  static async cancelImport(taskId: string): Promise<boolean> {
    try {
      await invoke('cancel_import', { taskId })
      return true
    } catch (error) {
      console.error('Failed to cancel import:', error)
      return false
    }
  }

  /**
   * 获取导入结果
   */
  static async getImportResult(taskId: string): Promise<ImportResult> {
    try {
      const result = await invoke('get_import_result', { taskId })
      return result as ImportResult
    } catch (error) {
      console.error('Failed to get import result:', error)
      throw new Error(`获取导入结果失败: ${error}`)
    }
  }

  /**
   * 验证导入配置
   */
  static validateConfig(config: ImportMaterialConfig): string[] {
    const errors: string[] = []

    if (!config.projectId) {
      errors.push('项目ID不能为空')
    }

    if (!config.sourceDirectory) {
      errors.push('请选择素材目录')
    }

    if (config.fileTypes.length === 0) {
      errors.push('请至少选择一种文件类型')
    }

    if (config.enableAutoSegmentation) {
      const segConfig = config.segmentationConfig
      
      if (segConfig.sceneThreshold < 0 || segConfig.sceneThreshold > 1) {
        errors.push('场景变化阈值必须在0-1之间')
      }

      if (segConfig.timeInterval <= 0) {
        errors.push('时间间隔必须大于0')
      }

      if (segConfig.minSegmentDuration <= 0) {
        errors.push('最小片段时长必须大于0')
      }

      if (segConfig.maxSegmentDuration <= segConfig.minSegmentDuration) {
        errors.push('最大片段时长必须大于最小片段时长')
      }
    }

    return errors
  }

  /**
   * 估算导入时间
   */
  static estimateImportTime(fileCount: number, config: ImportMaterialConfig): number {
    // 基础导入时间（每个文件）
    let timePerFile = 5 // 秒

    // 自动分镜增加时间
    if (config.enableAutoSegmentation) {
      timePerFile += 15
    }

    // 生成缩略图增加时间
    if (config.generateThumbnails) {
      timePerFile += 3
    }

    // 元数据提取增加时间
    if (config.extractMetadata) {
      timePerFile += 2
    }

    // 自动标签增加时间
    if (config.autoTagging) {
      timePerFile += 5
    }

    return Math.round(fileCount * timePerFile)
  }

  /**
   * 获取支持的文件类型
   */
  static getSupportedFileTypes(): Array<{value: string, label: string, description: string}> {
    return [
      { value: 'mp4', label: 'MP4', description: '最常用的视频格式' },
      { value: 'avi', label: 'AVI', description: '经典视频格式' },
      { value: 'mov', label: 'MOV', description: 'QuickTime视频格式' },
      { value: 'mkv', label: 'MKV', description: '高质量视频格式' },
      { value: 'wmv', label: 'WMV', description: 'Windows媒体格式' },
      { value: 'flv', label: 'FLV', description: 'Flash视频格式' },
      { value: 'm4v', label: 'M4V', description: 'iTunes视频格式' },
      { value: 'webm', label: 'WebM', description: 'Web视频格式' },
      { value: '3gp', label: '3GP', description: '移动设备格式' }
    ]
  }

  /**
   * 获取分镜方法选项
   */
  static getSegmentationMethods(): Array<{value: string, label: string, description: string}> {
    return [
      { 
        value: 'smart', 
        label: '智能分镜', 
        description: '结合场景变化和时间间隔的智能分镜' 
      },
      { 
        value: 'scene', 
        label: '场景分镜', 
        description: '根据场景变化自动分镜' 
      },
      { 
        value: 'time', 
        label: '时间分镜', 
        description: '按固定时间间隔分镜' 
      }
    ]
  }

  /**
   * 预览分镜结果
   */
  static async previewSegmentation(
    filePath: string, 
    config: ImportMaterialConfig['segmentationConfig']
  ): Promise<Array<{start: number, end: number, thumbnail?: string}>> {
    try {
      const result = await invoke('preview_segmentation', { filePath, config })
      return result as Array<{start: number, end: number, thumbnail?: string}>
    } catch (error) {
      console.error('Failed to preview segmentation:', error)
      throw new Error(`预览分镜失败: ${error}`)
    }
  }
}
