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>,
    /// SDK 配置
    pub sdk_config: ComfyUISDKConfig,
}

/// ComfyUI SDK 配置
/// 控制 SDK 的使用和行为
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ComfyUISDKConfig {
    /// 是否优先使用 SDK
    pub prefer_sdk: bool,
    /// 当 SDK 失败时是否回退到传统实现
    pub fallback_to_legacy: bool,
    /// SDK 执行超时时间（秒）
    pub sdk_timeout_seconds: u64,
    /// SDK 重试次数
    pub sdk_retry_attempts: u32,
    /// 是否启用详细日志
    pub enable_verbose_logging: bool,
    /// 是否启用进度回调
    pub enable_progress_callback: bool,
}

#[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 ComfyUISDKConfig {
    fn default() -> Self {
        ComfyUISDKConfig {
            prefer_sdk: true,
            fallback_to_legacy: true,
            sdk_timeout_seconds: 300,
            sdk_retry_attempts: 3,
            enable_verbose_logging: false,
            enable_progress_callback: 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,
            sdk_config: ComfyUISDKConfig::default(),
        }
    }
}

impl ComfyUISettings {
    /// 获取完整的 ComfyUI 服务 URL
    pub fn base_url(&self) -> String {
        format!("http://{}:{}", self.server_address, self.server_port)
    }

    /// 检查是否启用了 SDK
    pub fn is_sdk_enabled(&self) -> bool {
        self.enabled && self.sdk_config.prefer_sdk
    }

    /// 获取 SDK 超时时间
    pub fn get_sdk_timeout(&self) -> std::time::Duration {
        std::time::Duration::from_secs(self.sdk_config.sdk_timeout_seconds)
    }

    /// 转换为新的 ComfyUI 配置
    pub fn to_comfyui_config(&self) -> crate::data::models::comfyui::ComfyUIConfig {
        use crate::data::models::comfyui::ComfyUIConfig;

        ComfyUIConfig {
            base_url: self.base_url(),
            timeout_seconds: self.timeout_seconds,
            retry_attempts: self.sdk_config.sdk_retry_attempts,
            retry_delay_ms: 1000, // 默认 1 秒重试延迟
            enable_websocket: true, // 默认启用 WebSocket
            enable_cache: true, // 默认启用缓存
            max_concurrency: 4, // 默认并发数
            custom_headers: None, // 暂时不支持自定义头
        }
    }

    /// 从新的 ComfyUI 配置更新设置
    pub fn update_from_comfyui_config(&mut self, config: &crate::data::models::comfyui::ComfyUIConfig) {
        // 解析 URL
        if let Ok(url) = url::Url::parse(&config.base_url) {
            if let Some(host) = url.host_str() {
                self.server_address = host.to_string();
            }
            if let Some(port) = url.port() {
                self.server_port = port;
            }
        }

        self.timeout_seconds = config.timeout_seconds;
        self.sdk_config.sdk_retry_attempts = config.retry_attempts;
    }

    /// 验证配置
    pub fn validate(&self) -> crate::data::models::comfyui::ValidationResult {
        use crate::data::models::comfyui::{ValidationResult, SDKValidationError as ValidationError};

        let mut result = ValidationResult::success();

        // 验证服务器地址
        if self.server_address.trim().is_empty() {
            result.add_error(ValidationError::new("server_address", "服务器地址不能为空"));
        }

        // 验证端口
        if self.server_port == 0 {
            result.add_error(ValidationError::new("server_port", "端口号必须大于 0"));
        }

        // 验证超时时间
        if self.timeout_seconds == 0 {
            result.add_error(ValidationError::new("timeout_seconds", "超时时间必须大于 0"));
        }

        // 验证 SDK 配置
        if self.sdk_config.sdk_retry_attempts > 10 {
            result.add_error(ValidationError::new("sdk_retry_attempts", "重试次数不应超过 10"));
        }

        if self.sdk_config.sdk_timeout_seconds == 0 {
            result.add_error(ValidationError::new("sdk_timeout_seconds", "SDK 超时时间必须大于 0"));
        }

        result
    }
}

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,
}
