/**
 * 混剪服务
 * 处理一键混剪相关的业务逻辑
 */

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

export interface MixEditConfig {
  // 基础配置
  duration: number // 目标时长（秒）
  style: 'auto' | 'fast' | 'smooth' | 'dynamic' // 剪辑风格
  music: boolean // 是否添加背景音乐
  
  // 素材配置
  useAllMaterials: boolean // 是否使用所有素材
  selectedMaterialIds: string[] // 选中的素材ID
  
  // 模特配置
  useAllModels: boolean // 是否使用所有模特
  selectedModelIds: string[] // 选中的模特ID
  
  // 高级配置
  transitionType: 'cut' | 'fade' | 'slide' | 'zoom' // 转场类型
  textOverlay: boolean // 是否添加文字叠加
  logoWatermark: boolean // 是否添加Logo水印
}

export interface MixEditResult {
  success: boolean
  message: string
  outputPath?: string
  duration?: number
  segmentCount?: number
  previewUrl?: string
}

export interface MixEditProgress {
  stage: 'preparing' | 'analyzing' | 'editing' | 'rendering' | 'completed' | 'error'
  progress: number // 0-100
  message: string
  currentSegment?: number
  totalSegments?: number
}

export class MixEditService {
  /**
   * 获取默认混剪配置
   */
  static getDefaultConfig(): MixEditConfig {
    return {
      duration: 60, // 默认60秒
      style: 'auto',
      music: true,
      useAllMaterials: true,
      selectedMaterialIds: [],
      useAllModels: true,
      selectedModelIds: [],
      transitionType: 'fade',
      textOverlay: false,
      logoWatermark: false,
    }
  }

  /**
   * 验证混剪配置
   */
  static validateConfig(config: MixEditConfig, materials: VideoSegment[], models: Model[]): string[] {
    const errors: string[] = []

    if (config.duration <= 0) {
      errors.push('目标时长必须大于0')
    }

    if (!config.useAllMaterials && config.selectedMaterialIds.length === 0) {
      errors.push('请至少选择一个素材')
    }

    if (!config.useAllModels && config.selectedModelIds.length === 0) {
      errors.push('请至少选择一个模特')
    }

    const availableMaterials = config.useAllMaterials 
      ? materials 
      : materials.filter(m => config.selectedMaterialIds.includes(m.id))

    if (availableMaterials.length === 0) {
      errors.push('没有可用的素材')
    }

    const totalMaterialDuration = availableMaterials.reduce((sum, m) => sum + (m.duration || 0), 0)
    if (totalMaterialDuration < config.duration) {
      errors.push(`素材总时长(${totalMaterialDuration}s)小于目标时长(${config.duration}s)`)
    }

    return errors
  }

  /**
   * 开始一键混剪
   */
  static async startMixEdit(
    project: Project,
    config: MixEditConfig,
    materials: VideoSegment[],
    models: Model[]
  ): Promise<MixEditResult> {
    try {
      // 验证配置
      const errors = this.validateConfig(config, materials, models)
      if (errors.length > 0) {
        return {
          success: false,
          message: `配置错误: ${errors.join(', ')}`
        }
      }

      // 准备混剪参数
      const mixEditParams = {
        projectId: project.id,
        projectName: project.name,
        config,
        materials: config.useAllMaterials 
          ? materials 
          : materials.filter(m => config.selectedMaterialIds.includes(m.id)),
        models: config.useAllModels 
          ? models 
          : models.filter(m => config.selectedModelIds.includes(m.id))
      }

      // 调用后端混剪服务
      const result = await invoke('start_mix_edit', { params: mixEditParams })
      
      return result as MixEditResult
    } catch (error) {
      console.error('Mix edit failed:', error)
      return {
        success: false,
        message: `混剪失败: ${error}`
      }
    }
  }

  /**
   * 获取混剪进度
   */
  static async getMixEditProgress(taskId: string): Promise<MixEditProgress> {
    try {
      const progress = await invoke('get_mix_edit_progress', { taskId })
      return progress as MixEditProgress
    } catch (error) {
      console.error('Failed to get mix edit progress:', error)
      return {
        stage: 'error',
        progress: 0,
        message: `获取进度失败: ${error}`
      }
    }
  }

  /**
   * 取消混剪任务
   */
  static async cancelMixEdit(taskId: string): Promise<boolean> {
    try {
      await invoke('cancel_mix_edit', { taskId })
      return true
    } catch (error) {
      console.error('Failed to cancel mix edit:', error)
      return false
    }
  }

  /**
   * 获取混剪预设
   */
  static getMixEditPresets(): Array<{name: string, config: Partial<MixEditConfig>}> {
    return [
      {
        name: '快速剪辑',
        config: {
          duration: 30,
          style: 'fast',
          transitionType: 'cut',
          music: true,
          textOverlay: false
        }
      },
      {
        name: '平滑过渡',
        config: {
          duration: 60,
          style: 'smooth',
          transitionType: 'fade',
          music: true,
          textOverlay: true
        }
      },
      {
        name: '动感剪辑',
        config: {
          duration: 45,
          style: 'dynamic',
          transitionType: 'zoom',
          music: true,
          textOverlay: true
        }
      },
      {
        name: '长视频',
        config: {
          duration: 120,
          style: 'auto',
          transitionType: 'slide',
          music: true,
          textOverlay: false
        }
      }
    ]
  }

  /**
   * 估算混剪时间
   */
  static estimateMixEditTime(config: MixEditConfig, materialCount: number): number {
    // 基础时间（秒）
    let estimatedTime = 30

    // 根据目标时长调整
    estimatedTime += config.duration * 0.5

    // 根据素材数量调整
    estimatedTime += materialCount * 2

    // 根据剪辑风格调整
    switch (config.style) {
      case 'fast':
        estimatedTime *= 0.8
        break
      case 'dynamic':
        estimatedTime *= 1.2
        break
      case 'smooth':
        estimatedTime *= 1.1
        break
    }

    // 根据特效调整
    if (config.textOverlay) estimatedTime *= 1.1
    if (config.logoWatermark) estimatedTime *= 1.05
    if (config.music) estimatedTime *= 1.1

    return Math.round(estimatedTime)
  }
}
