//! Topaz Video AI 滤镜组合库
//! 
//! 提供易用的高级滤镜组合函数，封装复杂的 TVAI 滤镜参数

pub mod combinations;
pub mod presets;
pub mod builder;

use std::path::Path;
use crate::core::{TvaiError, TvaiProcessor, ProcessResult, ProgressCallback};
use crate::config::UpscaleModel;

/// 滤镜组合类型
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum FilterCombination {
    /// 超分辨率放大
    Upscale {
        model: UpscaleModel,
        scale: f32,
        quality: QualityLevel,
    },
    /// 帧插值慢动作
    SlowMotion {
        factor: f32,
        quality: QualityLevel,
    },
    /// 视频稳定化
    Stabilize {
        strength: f32,
        quality: QualityLevel,
    },
    /// 完整增强 (放大 + 稳定化)
    FullEnhance {
        upscale_factor: f32,
        stabilize: bool,
        quality: QualityLevel,
    },
    /// 老视频修复
    RestoreOldVideo {
        upscale_factor: f32,
        denoise_level: f32,
        quality: QualityLevel,
    },
    /// 游戏录像优化
    GameFootage {
        upscale_factor: f32,
        sharpen: bool,
        quality: QualityLevel,
    },
}

/// 质量等级
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub enum QualityLevel {
    /// 快速处理
    Fast,
    /// 平衡质量和速度
    Balanced,
    /// 高质量
    High,
    /// 最高质量
    Maximum,
}

/// 处理选项
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProcessOptions {
    /// 输出格式 (mp4, mov, avi 等)
    pub output_format: Option<String>,
    /// 是否保留音频
    pub keep_audio: bool,
    /// 自定义输出分辨率
    pub output_resolution: Option<(u32, u32)>,
    /// GPU 设备索引 (-2=自动, -1=CPU, 0+=GPU)
    pub device: i32,
    /// VRAM 使用限制 (0.1-1.0)
    pub vram_limit: f32,
    /// 是否启用进度回调
    pub enable_progress: bool,
}

impl Default for ProcessOptions {
    fn default() -> Self {
        Self {
            output_format: None,
            keep_audio: true,
            output_resolution: None,
            device: -2, // 自动选择
            vram_limit: 1.0,
            enable_progress: true,
        }
    }
}

/// 滤镜组合处理器
pub struct FilterProcessor {
    processor: TvaiProcessor,
}

impl FilterProcessor {
    /// 创建新的滤镜处理器
    pub fn new(processor: TvaiProcessor) -> Self {
        Self { processor }
    }

    /// 应用滤镜组合到视频
    pub async fn apply_to_video(
        &mut self,
        input_path: &Path,
        output_path: &Path,
        combination: FilterCombination,
        options: ProcessOptions,
        progress_callback: Option<&ProgressCallback>,
    ) -> Result<ProcessResult, TvaiError> {
        match combination {
            FilterCombination::Upscale { model, scale, quality } => {
                self.apply_upscale(input_path, output_path, model, scale, quality, options, progress_callback).await
            }
            FilterCombination::SlowMotion { factor, quality } => {
                self.apply_slow_motion(input_path, output_path, factor, quality, options, progress_callback).await
            }
            FilterCombination::Stabilize { strength, quality } => {
                self.apply_stabilize(input_path, output_path, strength, quality, options, progress_callback).await
            }
            FilterCombination::FullEnhance { upscale_factor, stabilize, quality } => {
                self.apply_full_enhance(input_path, output_path, upscale_factor, stabilize, quality, options, progress_callback).await
            }
            FilterCombination::RestoreOldVideo { upscale_factor, denoise_level, quality } => {
                self.apply_restore_old_video(input_path, output_path, upscale_factor, denoise_level, quality, options, progress_callback).await
            }
            FilterCombination::GameFootage { upscale_factor, sharpen, quality } => {
                self.apply_game_footage(input_path, output_path, upscale_factor, sharpen, quality, options, progress_callback).await
            }
        }
    }

    /// 应用滤镜组合到图片
    pub async fn apply_to_image(
        &mut self,
        input_path: &Path,
        output_path: &Path,
        combination: FilterCombination,
        options: ProcessOptions,
        progress_callback: Option<&ProgressCallback>,
    ) -> Result<ProcessResult, TvaiError> {
        match combination {
            FilterCombination::Upscale { model, scale, quality } => {
                self.apply_image_upscale(input_path, output_path, model, scale, quality, options, progress_callback).await
            }
            _ => Err(TvaiError::InvalidParameter(
                "This filter combination is not supported for images".to_string()
            ))
        }
    }

    /// 获取推荐的滤镜组合
    pub async fn get_recommended_combination(
        &self,
        input_path: &Path,
    ) -> Result<FilterCombination, TvaiError> {
        // 获取视频信息
        let video_info = crate::utils::get_video_info(input_path).await?;
        
        // 基于视频特征推荐组合
        if video_info.width < 720 || video_info.height < 480 {
            // 低分辨率视频，推荐老视频修复
            Ok(FilterCombination::RestoreOldVideo {
                upscale_factor: 2.0,
                denoise_level: 0.3,
                quality: QualityLevel::High,
            })
        } else if video_info.width >= 1920 && video_info.fps > 30.0 {
            // 高分辨率高帧率，可能是游戏录像
            Ok(FilterCombination::GameFootage {
                upscale_factor: 1.5,
                sharpen: true,
                quality: QualityLevel::Balanced,
            })
        } else if video_info.fps < 24.0 {
            // 低帧率视频，推荐帧插值
            Ok(FilterCombination::SlowMotion {
                factor: 2.0,
                quality: QualityLevel::High,
            })
        } else {
            // 通用增强
            Ok(FilterCombination::FullEnhance {
                upscale_factor: 1.5,
                stabilize: true,
                quality: QualityLevel::Balanced,
            })
        }
    }
}

/// 快速处理函数
pub mod quick {
    use super::*;

    /// 快速视频放大
    pub async fn upscale_video(
        input: &Path,
        output: &Path,
        scale: f32,
    ) -> Result<ProcessResult, TvaiError> {
        let combination = FilterCombination::Upscale {
            model: UpscaleModel::Iris3,
            scale,
            quality: QualityLevel::Balanced,
        };
        
        let processor = create_default_processor().await?;
        let mut filter_processor = FilterProcessor::new(processor);
        
        filter_processor.apply_to_video(
            input,
            output,
            combination,
            ProcessOptions::default(),
            None,
        ).await
    }

    /// 快速慢动作处理
    pub async fn slow_motion(
        input: &Path,
        output: &Path,
        factor: f32,
    ) -> Result<ProcessResult, TvaiError> {
        let combination = FilterCombination::SlowMotion {
            factor,
            quality: QualityLevel::Balanced,
        };
        
        let processor = create_default_processor().await?;
        let mut filter_processor = FilterProcessor::new(processor);
        
        filter_processor.apply_to_video(
            input,
            output,
            combination,
            ProcessOptions::default(),
            None,
        ).await
    }

    /// 快速视频稳定化
    pub async fn stabilize_video(
        input: &Path,
        output: &Path,
        strength: f32,
    ) -> Result<ProcessResult, TvaiError> {
        let combination = FilterCombination::Stabilize {
            strength,
            quality: QualityLevel::Balanced,
        };
        
        let processor = create_default_processor().await?;
        let mut filter_processor = FilterProcessor::new(processor);
        
        filter_processor.apply_to_video(
            input,
            output,
            combination,
            ProcessOptions::default(),
            None,
        ).await
    }

    /// 创建默认处理器
    async fn create_default_processor() -> Result<TvaiProcessor, TvaiError> {
        let topaz_path = crate::utils::detect_topaz_installation()
            .ok_or_else(|| TvaiError::TopazNotFound("Topaz Video AI not found".to_string()))?;

        let config = crate::core::TvaiConfig::builder()
            .topaz_path(topaz_path)
            .use_gpu(true)
            .build()?;

        TvaiProcessor::new(config)
    }
}
