use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// 应用配置结构
/// 遵循 Tauri 开发规范的配置管理模式
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppConfig {
    pub theme: String,
    pub language: String,
    pub auto_save: bool,
    pub window_size: WindowSize,
    pub recent_projects: Vec<String>,
    pub default_project_path: Option<String>,
    pub directory_settings: DirectorySettings,
    pub comfyui_settings: ComfyUISettings,
}

/// 全局目录设置
/// 存储各种导入导出操作的默认目录路径
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DirectorySettings {
    /// 素材导入默认目录
    pub material_import_directory: Option<String>,
    /// 模板导入默认目录
    pub template_import_directory: Option<String>,
    /// 剪影导出默认目录
    pub jianying_export_directory: Option<String>,
    /// 项目导出默认目录
    pub project_export_directory: Option<String>,
    /// 缩略图导出默认目录
    pub thumbnail_export_directory: Option<String>,
    /// 是否启用自动记忆功能
    pub auto_remember_directories: bool,
}

/// ComfyUI 全局设置
/// 存储 ComfyUI 服务连接和配置信息
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ComfyUISettings {
    /// ComfyUI 服务地址
    pub server_address: String,
    /// ComfyUI 服务端口号
    pub server_port: u16,
    /// 是否为本地服务
    pub is_local: bool,
    /// 连接超时时间（秒）
    pub timeout_seconds: u64,
    /// 是否启用 ComfyUI 功能
    pub enabled: bool,
    /// 工作流文件存储目录
    pub workflow_directory: Option<String>,
    /// 输出文件存储目录
    pub output_directory: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct WindowSize {
    pub width: f64,
    pub height: f64,
}

impl Default for DirectorySettings {
    fn default() -> Self {
        DirectorySettings {
            material_import_directory: None,
            template_import_directory: None,
            jianying_export_directory: None,
            project_export_directory: None,
            thumbnail_export_directory: None,
            auto_remember_directories: true,
        }
    }
}

impl Default for ComfyUISettings {
    fn default() -> Self {
        ComfyUISettings {
            server_address: "127.0.0.1".to_string(),
            server_port: 8188,
            is_local: true,
            timeout_seconds: 300,
            enabled: false,
            workflow_directory: None,
            output_directory: None,
        }
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        AppConfig {
            theme: "light".to_string(),
            language: "zh-CN".to_string(),
            auto_save: true,
            window_size: WindowSize {
                width: 1200.0,
                height: 800.0,
            },
            recent_projects: Vec::new(),
            default_project_path: None,
            directory_settings: DirectorySettings::default(),
            comfyui_settings: ComfyUISettings::default(),
        }
    }
}

impl AppConfig {
    /// 加载配置文件
    pub fn load() -> Self {
        let config_path = Self::get_config_path();
        
        if config_path.exists() {
            match std::fs::read_to_string(&config_path) {
                Ok(content) => {
                    match serde_json::from_str(&content) {
                        Ok(config) => config,
                        Err(_) => Self::default(),
                    }
                }
                Err(_) => Self::default(),
            }
        } else {
            Self::default()
        }
    }

    /// 保存配置文件
    pub fn save(&self) -> anyhow::Result<()> {
        let config_path = Self::get_config_path();
        
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        
        let content = serde_json::to_string_pretty(self)?;
        std::fs::write(config_path, content)?;
        
        Ok(())
    }

    /// 获取配置文件路径
    fn get_config_path() -> PathBuf {
        // 使用标准的应用数据目录
        if let Some(data_dir) = dirs::data_dir() {
            data_dir.join("mixvideo").join("config.json")
        } else {
            PathBuf::from(".").join("config.json")
        }
    }

    /// 添加最近项目
    pub fn add_recent_project(&mut self, project_path: String) {
        self.recent_projects.retain(|p| p != &project_path);
        self.recent_projects.insert(0, project_path);

        // 保持最近项目列表不超过10个
        if self.recent_projects.len() > 10 {
            self.recent_projects.truncate(10);
        }
    }

    /// 更新目录设置
    pub fn update_directory_setting(&mut self, setting_type: DirectorySettingType, path: String) {
        match setting_type {
            DirectorySettingType::MaterialImport => {
                self.directory_settings.material_import_directory = Some(path);
            }
            DirectorySettingType::TemplateImport => {
                self.directory_settings.template_import_directory = Some(path);
            }
            DirectorySettingType::JianyingExport => {
                self.directory_settings.jianying_export_directory = Some(path);
            }
            DirectorySettingType::ProjectExport => {
                self.directory_settings.project_export_directory = Some(path);
            }
            DirectorySettingType::ThumbnailExport => {
                self.directory_settings.thumbnail_export_directory = Some(path);
            }
        }
    }

    /// 获取目录设置
    pub fn get_directory_setting(&self, setting_type: DirectorySettingType) -> Option<&String> {
        match setting_type {
            DirectorySettingType::MaterialImport => {
                self.directory_settings.material_import_directory.as_ref()
            }
            DirectorySettingType::TemplateImport => {
                self.directory_settings.template_import_directory.as_ref()
            }
            DirectorySettingType::JianyingExport => {
                self.directory_settings.jianying_export_directory.as_ref()
            }
            DirectorySettingType::ProjectExport => {
                self.directory_settings.project_export_directory.as_ref()
            }
            DirectorySettingType::ThumbnailExport => {
                self.directory_settings.thumbnail_export_directory.as_ref()
            }
        }
    }

    /// 更新 ComfyUI 设置
    pub fn update_comfyui_settings(&mut self, settings: ComfyUISettings) {
        self.comfyui_settings = settings;
    }

    /// 获取 ComfyUI 设置
    pub fn get_comfyui_settings(&self) -> &ComfyUISettings {
        &self.comfyui_settings
    }

    /// 获取 ComfyUI 服务器 URL
    pub fn get_comfyui_server_url(&self) -> String {
        format!("{}:{}", self.comfyui_settings.server_address, self.comfyui_settings.server_port)
    }

    /// 检查 ComfyUI 是否启用
    pub fn is_comfyui_enabled(&self) -> bool {
        self.comfyui_settings.enabled
    }
}

/// 目录设置类型枚举
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DirectorySettingType {
    MaterialImport,
    TemplateImport,
    JianyingExport,
    ProjectExport,
    ThumbnailExport,
}
