//! 滤镜组合构建器

use super::{FilterCombination, QualityLevel, ProcessOptions};
use crate::config::UpscaleModel;

/// 滤镜组合构建器
pub struct FilterCombinationBuilder {
    combination_type: Option<CombinationType>,
    quality: QualityLevel,
    options: ProcessOptions,
}

#[derive(Debug)]
enum CombinationType {
    Upscale {
        model: UpscaleModel,
        scale: f32,
    },
    SlowMotion {
        factor: f32,
    },
    Stabilize {
        strength: f32,
    },
    FullEnhance {
        upscale_factor: f32,
        stabilize: bool,
    },
    RestoreOldVideo {
        upscale_factor: f32,
        denoise_level: f32,
    },
    GameFootage {
        upscale_factor: f32,
        sharpen: bool,
    },
}

impl FilterCombinationBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            combination_type: None,
            quality: QualityLevel::Balanced,
            options: ProcessOptions::default(),
        }
    }

    /// 设置超分辨率放大
    pub fn upscale(mut self, model: UpscaleModel, scale: f32) -> Self {
        self.combination_type = Some(CombinationType::Upscale { model, scale });
        self
    }

    /// 设置慢动作处理
    pub fn slow_motion(mut self, factor: f32) -> Self {
        self.combination_type = Some(CombinationType::SlowMotion { factor });
        self
    }

    /// 设置视频稳定化
    pub fn stabilize(mut self, strength: f32) -> Self {
        self.combination_type = Some(CombinationType::Stabilize { strength });
        self
    }

    /// 设置完整增强
    pub fn full_enhance(mut self, upscale_factor: f32, stabilize: bool) -> Self {
        self.combination_type = Some(CombinationType::FullEnhance { upscale_factor, stabilize });
        self
    }

    /// 设置老视频修复
    pub fn restore_old_video(mut self, upscale_factor: f32, denoise_level: f32) -> Self {
        self.combination_type = Some(CombinationType::RestoreOldVideo { upscale_factor, denoise_level });
        self
    }

    /// 设置游戏录像优化
    pub fn game_footage(mut self, upscale_factor: f32, sharpen: bool) -> Self {
        self.combination_type = Some(CombinationType::GameFootage { upscale_factor, sharpen });
        self
    }

    /// 设置质量等级
    pub fn quality(mut self, quality: QualityLevel) -> Self {
        self.quality = quality;
        self
    }

    /// 设置输出格式
    pub fn output_format(mut self, format: String) -> Self {
        self.options.output_format = Some(format);
        self
    }

    /// 设置是否保留音频
    pub fn keep_audio(mut self, keep: bool) -> Self {
        self.options.keep_audio = keep;
        self
    }

    /// 设置输出分辨率
    pub fn output_resolution(mut self, width: u32, height: u32) -> Self {
        self.options.output_resolution = Some((width, height));
        self
    }

    /// 设置设备
    pub fn device(mut self, device: i32) -> Self {
        self.options.device = device;
        self
    }

    /// 设置 VRAM 限制
    pub fn vram_limit(mut self, limit: f32) -> Self {
        self.options.vram_limit = limit;
        self
    }

    /// 启用进度回调
    pub fn enable_progress(mut self, enable: bool) -> Self {
        self.options.enable_progress = enable;
        self
    }

    /// 构建滤镜组合和选项
    pub fn build(self) -> Result<(FilterCombination, ProcessOptions), String> {
        let combination_type = self.combination_type
            .ok_or_else(|| "No filter combination type specified".to_string())?;

        let combination = match combination_type {
            CombinationType::Upscale { model, scale } => {
                FilterCombination::Upscale {
                    model,
                    scale,
                    quality: self.quality,
                }
            }
            CombinationType::SlowMotion { factor } => {
                FilterCombination::SlowMotion {
                    factor,
                    quality: self.quality,
                }
            }
            CombinationType::Stabilize { strength } => {
                FilterCombination::Stabilize {
                    strength,
                    quality: self.quality,
                }
            }
            CombinationType::FullEnhance { upscale_factor, stabilize } => {
                FilterCombination::FullEnhance {
                    upscale_factor,
                    stabilize,
                    quality: self.quality,
                }
            }
            CombinationType::RestoreOldVideo { upscale_factor, denoise_level } => {
                FilterCombination::RestoreOldVideo {
                    upscale_factor,
                    denoise_level,
                    quality: self.quality,
                }
            }
            CombinationType::GameFootage { upscale_factor, sharpen } => {
                FilterCombination::GameFootage {
                    upscale_factor,
                    sharpen,
                    quality: self.quality,
                }
            }
        };

        Ok((combination, self.options))
    }
}

impl Default for FilterCombinationBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 快速构建器函数
pub mod quick_builders {
    use super::*;

    /// 快速创建超分辨率放大组合
    pub fn upscale(scale: f32) -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Iris3, scale)
            .quality(QualityLevel::Balanced)
    }

    /// 快速创建高质量超分辨率放大组合
    pub fn upscale_hq(scale: f32) -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Ahq12, scale)
            .quality(QualityLevel::High)
    }

    /// 快速创建慢动作组合
    pub fn slow_motion(factor: f32) -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .slow_motion(factor)
            .quality(QualityLevel::Balanced)
    }

    /// 快速创建视频稳定化组合
    pub fn stabilize() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .stabilize(1.0)
            .quality(QualityLevel::Balanced)
    }

    /// 快速创建完整增强组合
    pub fn full_enhance() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .full_enhance(2.0, true)
            .quality(QualityLevel::High)
    }

    /// 快速创建老视频修复组合
    pub fn restore_old_video() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .restore_old_video(2.0, 0.3)
            .quality(QualityLevel::High)
    }

    /// 快速创建游戏录像优化组合
    pub fn game_footage() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .game_footage(1.5, true)
            .quality(QualityLevel::High)
    }

    /// 快速创建社交媒体优化组合
    pub fn social_media() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Iris3, 2.0)
            .quality(QualityLevel::Balanced)
            .output_resolution(1920, 1080)
            .output_format("mp4".to_string())
    }

    /// 快速创建人像优化组合
    pub fn portrait() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Nyx3, 2.0)
            .quality(QualityLevel::High)
    }

    /// 快速创建动画优化组合
    pub fn animation() -> FilterCombinationBuilder {
        FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Iris3, 2.0)
            .quality(QualityLevel::High)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder_upscale() {
        let (combination, options) = FilterCombinationBuilder::new()
            .upscale(UpscaleModel::Iris3, 2.0)
            .quality(QualityLevel::High)
            .output_format("mp4".to_string())
            .build()
            .unwrap();

        match combination {
            FilterCombination::Upscale { model, scale, quality } => {
                assert_eq!(model, UpscaleModel::Iris3);
                assert_eq!(scale, 2.0);
                assert!(matches!(quality, QualityLevel::High));
            }
            _ => panic!("Expected Upscale combination"),
        }

        assert_eq!(options.output_format, Some("mp4".to_string()));
    }

    #[test]
    fn test_quick_builders() {
        let (combination, _) = quick_builders::upscale(2.0).build().unwrap();
        
        match combination {
            FilterCombination::Upscale { model, scale, .. } => {
                assert_eq!(model, UpscaleModel::Iris3);
                assert_eq!(scale, 2.0);
            }
            _ => panic!("Expected Upscale combination"),
        }
    }

    #[test]
    fn test_builder_validation() {
        let result = FilterCombinationBuilder::new().build();
        assert!(result.is_err());
    }
}
