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

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

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

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);
        }
    }
}
