//! 预设配置

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

/// 预设类型
#[derive(Debug, Clone)]
pub enum PresetType {
    /// 社交媒体优化
    SocialMedia,
    /// 电影修复
    FilmRestoration,
    /// 游戏录像
    Gaming,
    /// 监控视频
    Surveillance,
    /// 动画内容
    Animation,
    /// 人像视频
    Portrait,
    /// 风景视频
    Landscape,
    /// 快速预览
    QuickPreview,
}

impl PresetType {
    /// 获取预设的滤镜组合
    pub fn get_filter_combination(&self) -> FilterCombination {
        match self {
            PresetType::SocialMedia => FilterCombination::Upscale {
                model: UpscaleModel::Iris3,
                scale: 2.0,
                quality: QualityLevel::Balanced,
            },
            PresetType::FilmRestoration => FilterCombination::RestoreOldVideo {
                upscale_factor: 2.0,
                denoise_level: 0.4,
                quality: QualityLevel::High,
            },
            PresetType::Gaming => FilterCombination::GameFootage {
                upscale_factor: 1.5,
                sharpen: true,
                quality: QualityLevel::High,
            },
            PresetType::Surveillance => FilterCombination::RestoreOldVideo {
                upscale_factor: 2.0,
                denoise_level: 0.6,
                quality: QualityLevel::Balanced,
            },
            PresetType::Animation => FilterCombination::Upscale {
                model: UpscaleModel::Iris3,
                scale: 2.0,
                quality: QualityLevel::High,
            },
            PresetType::Portrait => FilterCombination::Upscale {
                model: UpscaleModel::Nyx3,
                scale: 2.0,
                quality: QualityLevel::High,
            },
            PresetType::Landscape => FilterCombination::FullEnhance {
                upscale_factor: 1.5,
                stabilize: true,
                quality: QualityLevel::High,
            },
            PresetType::QuickPreview => FilterCombination::Upscale {
                model: UpscaleModel::Alqs2,
                scale: 1.5,
                quality: QualityLevel::Fast,
            },
        }
    }

    /// 获取预设的处理选项
    pub fn get_process_options(&self) -> ProcessOptions {
        match self {
            PresetType::SocialMedia => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: Some((1920, 1080)),
                device: -2,
                vram_limit: 0.8,
                enable_progress: true,
            },
            PresetType::FilmRestoration => ProcessOptions {
                output_format: Some("mov".to_string()),
                keep_audio: true,
                output_resolution: None,
                device: -2,
                vram_limit: 1.0,
                enable_progress: true,
            },
            PresetType::Gaming => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: None,
                device: 0, // 优先使用 GPU
                vram_limit: 1.0,
                enable_progress: true,
            },
            PresetType::Surveillance => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: false,
                output_resolution: None,
                device: -2,
                vram_limit: 0.6,
                enable_progress: true,
            },
            PresetType::Animation => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: None,
                device: -2,
                vram_limit: 0.9,
                enable_progress: true,
            },
            PresetType::Portrait => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: None,
                device: -2,
                vram_limit: 0.8,
                enable_progress: true,
            },
            PresetType::Landscape => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: None,
                device: -2,
                vram_limit: 1.0,
                enable_progress: true,
            },
            PresetType::QuickPreview => ProcessOptions {
                output_format: Some("mp4".to_string()),
                keep_audio: true,
                output_resolution: Some((1280, 720)),
                device: -2,
                vram_limit: 0.5,
                enable_progress: true,
            },
        }
    }

    /// 获取预设描述
    pub fn description(&self) -> &'static str {
        match self {
            PresetType::SocialMedia => "优化用于社交媒体分享的视频，平衡质量和文件大小",
            PresetType::FilmRestoration => "修复老电影和胶片视频，去除噪点和伪影",
            PresetType::Gaming => "优化游戏录像，增强细节和锐度",
            PresetType::Surveillance => "增强监控视频质量，去除噪点",
            PresetType::Animation => "优化动画内容，保持清晰的线条和色彩",
            PresetType::Portrait => "优化人像视频，增强面部细节",
            PresetType::Landscape => "优化风景视频，增强细节并稳定画面",
            PresetType::QuickPreview => "快速预览模式，速度优先",
        }
    }

    /// 获取所有可用预设
    pub fn all_presets() -> Vec<PresetType> {
        vec![
            PresetType::SocialMedia,
            PresetType::FilmRestoration,
            PresetType::Gaming,
            PresetType::Surveillance,
            PresetType::Animation,
            PresetType::Portrait,
            PresetType::Landscape,
            PresetType::QuickPreview,
        ]
    }
}

/// 自定义预设构建器
pub struct PresetBuilder {
    combination: Option<FilterCombination>,
    options: ProcessOptions,
    name: String,
    description: String,
}

impl PresetBuilder {
    /// 创建新的预设构建器
    pub fn new(name: String) -> Self {
        Self {
            combination: None,
            options: ProcessOptions::default(),
            name,
            description: String::new(),
        }
    }

    /// 设置滤镜组合
    pub fn with_combination(mut self, combination: FilterCombination) -> Self {
        self.combination = Some(combination);
        self
    }

    /// 设置处理选项
    pub fn with_options(mut self, options: ProcessOptions) -> Self {
        self.options = options;
        self
    }

    /// 设置描述
    pub fn with_description(mut self, description: String) -> Self {
        self.description = description;
        self
    }

    /// 构建自定义预设
    pub fn build(self) -> Result<CustomPreset, String> {
        let combination = self.combination
            .ok_or_else(|| "Filter combination is required".to_string())?;

        Ok(CustomPreset {
            name: self.name,
            description: self.description,
            combination,
            options: self.options,
        })
    }
}

/// 自定义预设
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CustomPreset {
    pub name: String,
    pub description: String,
    pub combination: FilterCombination,
    pub options: ProcessOptions,
}

impl CustomPreset {
    /// 创建预设构建器
    pub fn builder(name: String) -> PresetBuilder {
        PresetBuilder::new(name)
    }

    /// 保存预设到文件
    pub fn save_to_file(&self, path: &std::path::Path) -> Result<(), Box<dyn std::error::Error>> {
        let json = serde_json::to_string_pretty(self)?;
        std::fs::write(path, json)?;
        Ok(())
    }

    /// 从文件加载预设
    pub fn load_from_file(path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
        let json = std::fs::read_to_string(path)?;
        let preset = serde_json::from_str(&json)?;
        Ok(preset)
    }
}

/// 预设管理器
pub struct PresetManager {
    custom_presets: Vec<CustomPreset>,
}

impl PresetManager {
    /// 创建新的预设管理器
    pub fn new() -> Self {
        Self {
            custom_presets: Vec::new(),
        }
    }

    /// 添加自定义预设
    pub fn add_custom_preset(&mut self, preset: CustomPreset) {
        self.custom_presets.push(preset);
    }

    /// 获取自定义预设
    pub fn get_custom_preset(&self, name: &str) -> Option<&CustomPreset> {
        self.custom_presets.iter().find(|p| p.name == name)
    }

    /// 列出所有自定义预设
    pub fn list_custom_presets(&self) -> &[CustomPreset] {
        &self.custom_presets
    }

    /// 删除自定义预设
    pub fn remove_custom_preset(&mut self, name: &str) -> bool {
        if let Some(pos) = self.custom_presets.iter().position(|p| p.name == name) {
            self.custom_presets.remove(pos);
            true
        } else {
            false
        }
    }

    /// 加载预设目录
    pub fn load_presets_from_dir(&mut self, dir: &std::path::Path) -> Result<usize, Box<dyn std::error::Error>> {
        let mut loaded = 0;
        
        if dir.exists() && dir.is_dir() {
            for entry in std::fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                
                if path.extension().and_then(|s| s.to_str()) == Some("json") {
                    match CustomPreset::load_from_file(&path) {
                        Ok(preset) => {
                            self.add_custom_preset(preset);
                            loaded += 1;
                        }
                        Err(e) => {
                            eprintln!("Failed to load preset from {}: {}", path.display(), e);
                        }
                    }
                }
            }
        }
        
        Ok(loaded)
    }
}

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