//! 主题系统模块
//! 
//! 支持主题切换、主题商店、自定义主题等功能

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// 主题元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeManifest {
    /// 主题唯一标识
    pub id: String,
    /// 主题名称
    pub name: String,
    /// 主题描述
    pub description: String,
    /// 主题版本
    pub version: String,
    /// 作者
    pub author: String,
    /// 主题类型
    pub theme_type: ThemeType,
    /// 预览图
    pub preview_image: Option<String>,
    /// CSS 文件路径
    pub css_file: Option<String>,
}

/// 主题类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ThemeType {
    /// 浅色主题
    Light,
    /// 深色主题
    Dark,
    /// 护眼主题
    EyeCare,
    /// 高对比度
    HighContrast,
    /// 自定义
    Custom,
}

/// 主题配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeConfig {
    /// 主背景色
    pub bg_primary: String,
    /// 次背景色
    pub bg_secondary: String,
    /// 第三背景色
    pub bg_tertiary: String,
    /// 主文字颜色
    pub text_primary: String,
    /// 次文字颜色
    pub text_secondary: String,
    /// 强调色
    pub accent_color: String,
    /// 强调色悬停
    pub accent_hover: String,
    /// 边框颜色
    pub border_color: String,
    /// 字体族
    pub font_family: String,
    /// 字体大小
    pub font_size: String,
    /// 行高
    pub line_height: String,
}

impl Default for ThemeConfig {
    fn default() -> Self {
        Self {
            bg_primary: "#1a1a1a".to_string(),
            bg_secondary: "#2a2a2a".to_string(),
            bg_tertiary: "#3a3a3a".to_string(),
            text_primary: "#e0e0e0".to_string(),
            text_secondary: "#b0b0b0".to_string(),
            accent_color: "#5a9fe0".to_string(),
            accent_hover: "#6aafef".to_string(),
            border_color: "#404040".to_string(),
            font_family: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif".to_string(),
            font_size: "16px".to_string(),
            line_height: "1.6".to_string(),
        }
    }
}

/// 内置主题
pub struct BuiltinThemes;

impl BuiltinThemes {
    /// 获取所有内置主题
    pub fn get_all() -> Vec<ThemeManifest> {
        vec![
            Self::dark_theme(),
            Self::light_theme(),
            Self::eye_care_theme(),
            Self::high_contrast_theme(),
        ]
    }
    
    /// 深色主题
    fn dark_theme() -> ThemeManifest {
        ThemeManifest {
            id: "com.readflow.theme.dark".to_string(),
            name: "深色模式".to_string(),
            description: "经典的深色主题，适合夜间阅读".to_string(),
            version: "1.0.0".to_string(),
            author: "ReadFlow Team".to_string(),
            theme_type: ThemeType::Dark,
            preview_image: None,
            css_file: None,
        }
    }
    
    /// 浅色主题
    fn light_theme() -> ThemeManifest {
        ThemeManifest {
            id: "com.readflow.theme.light".to_string(),
            name: "浅色模式".to_string(),
            description: "明亮的浅色主题，适合日间阅读".to_string(),
            version: "1.0.0".to_string(),
            author: "ReadFlow Team".to_string(),
            theme_type: ThemeType::Light,
            preview_image: None,
            css_file: None,
        }
    }
    
    /// 护眼主题
    fn eye_care_theme() -> ThemeManifest {
        ThemeManifest {
            id: "com.readflow.theme.eyecare".to_string(),
            name: "护眼模式".to_string(),
            description: "柔和的绿色调，减少眼睛疲劳".to_string(),
            version: "1.0.0".to_string(),
            author: "ReadFlow Team".to_string(),
            theme_type: ThemeType::EyeCare,
            preview_image: None,
            css_file: None,
        }
    }
    
    /// 高对比度主题
    fn high_contrast_theme() -> ThemeManifest {
        ThemeManifest {
            id: "com.readflow.theme.contrast".to_string(),
            name: "高对比度".to_string(),
            description: "增强对比度，提高可读性".to_string(),
            version: "1.0.0".to_string(),
            author: "ReadFlow Team".to_string(),
            theme_type: ThemeType::HighContrast,
            preview_image: None,
            css_file: None,
        }
    }
    
    /// 获取主题的 CSS 变量
    pub fn get_css_variables(theme_id: &str) -> String {
        match theme_id {
            "com.readflow.theme.dark" => Self::dark_css().to_string(),
            "com.readflow.theme.light" => Self::light_css().to_string(),
            "com.readflow.theme.eyecare" => Self::eyecare_css().to_string(),
            "com.readflow.theme.contrast" => Self::contrast_css().to_string(),
            _ => Self::dark_css().to_string(),
        }
    }
    
    fn dark_css() -> &'static str {
        r#"
:root {
    --bg-primary: #1a1a1a;
    --bg-secondary: #2a2a2a;
    --bg-tertiary: #3a3a3a;
    --text-primary: #e0e0e0;
    --text-secondary: #b0b0b0;
    --text-muted: #808080;
    --border-color: #404040;
    --accent-color: #5a9fe0;
    --accent-hover: #6aafef;
    --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
"#
    }
    
    fn light_css() -> &'static str {
        r#"
:root {
    --bg-primary: #ffffff;
    --bg-secondary: #f5f5f5;
    --bg-tertiary: #e8e8e8;
    --text-primary: #1a1a1a;
    --text-secondary: #4a4a4a;
    --text-muted: #8a8a8a;
    --border-color: #d0d0d0;
    --accent-color: #2196f3;
    --accent-hover: #1976d2;
    --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
"#
    }
    
    fn eyecare_css() -> &'static str {
        r#"
:root {
    --bg-primary: #f0f4e8;
    --bg-secondary: #e3e9d6;
    --bg-tertiary: #d4dcc4;
    --text-primary: #2d3a1e;
    --text-secondary: #4a5a36;
    --text-muted: #6b7a54;
    --border-color: #c5d4b0;
    --accent-color: #5a8f3a;
    --accent-hover: #4a7f2a;
    --shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
"#
    }
    
    fn contrast_css() -> &'static str {
        r#"
:root {
    --bg-primary: #000000;
    --bg-secondary: #1a1a1a;
    --bg-tertiary: #2a2a2a;
    --text-primary: #ffffff;
    --text-secondary: #f0f0f0;
    --text-muted: #cccccc;
    --border-color: #ffffff;
    --accent-color: #ffff00;
    --accent-hover: #ffff66;
    --shadow: 0 2px 8px rgba(255, 255, 255, 0.2);
}
"#
    }
}

/// 主题管理器
pub struct ThemeManager {
    /// 当前主题 ID
    current_theme_id: String,
    /// 主题目录
    themes_dir: PathBuf,
    /// 已安装的主题
    installed_themes: HashMap<String, ThemeManifest>,
    /// 主题配置
    configs: HashMap<String, ThemeConfig>,
}

impl ThemeManager {
    /// 创建主题管理器
    pub fn new(themes_dir: &str) -> Result<Self> {
        let themes_dir = PathBuf::from(themes_dir);
        
        if !themes_dir.exists() {
            std::fs::create_dir_all(&themes_dir)?;
        }
        
        let mut manager = Self {
            current_theme_id: "com.readflow.theme.dark".to_string(),
            themes_dir,
            installed_themes: HashMap::new(),
            configs: HashMap::new(),
        };
        
        // 扫描已安装的主题
        manager.scan_themes()?;
        
        Ok(manager)
    }
    
    /// 扫描主题目录
    pub fn scan_themes(&mut self) -> Result<()> {
        if !self.themes_dir.exists() {
            return Ok(());
        }
        
        for entry in std::fs::read_dir(&self.themes_dir)? {
            let entry = entry?;
            let path = entry.path();
            
            if !path.is_dir() {
                continue;
            }
            
            let manifest_path = path.join("manifest.json");
            if !manifest_path.exists() {
                continue;
            }
            
            let manifest_content = std::fs::read_to_string(&manifest_path)?;
            let manifest: ThemeManifest = serde_json::from_str(&manifest_content)?;
            
            self.installed_themes.insert(manifest.id.clone(), manifest);
        }
        
        Ok(())
    }
    
    /// 获取所有可用主题
    pub fn get_all_themes(&self) -> Vec<ThemeManifest> {
        let mut themes = BuiltinThemes::get_all();
        
        // 添加已安装的主题
        for theme in self.installed_themes.values() {
            themes.push(theme.clone());
        }
        
        themes
    }
    
    /// 获取当前主题
    pub fn get_current_theme(&self) -> String {
        self.current_theme_id.clone()
    }
    
    /// 设置当前主题
    pub fn set_current_theme(&mut self, theme_id: &str) -> Result<()> {
        // 验证主题是否存在
        let all_themes = self.get_all_themes();
        if !all_themes.iter().any(|t| t.id == theme_id) {
            anyhow::bail!("主题不存在：{}", theme_id);
        }
        
        self.current_theme_id = theme_id.to_string();
        Ok(())
    }
    
    /// 获取当前主题的 CSS
    pub fn get_current_css(&self) -> String {
        BuiltinThemes::get_css_variables(&self.current_theme_id)
    }
    
    /// 安装主题
    pub fn install_theme(&mut self, theme_path: &Path) -> Result<String> {
        let manifest_path = theme_path.join("manifest.json");
        let manifest_content = std::fs::read_to_string(&manifest_path)?;
        let manifest: ThemeManifest = serde_json::from_str(&manifest_content)?;
        
        // 复制到主题目录
        let target_path = self.themes_dir.join(&manifest.id);
        
        if target_path.exists() {
            anyhow::bail!("主题已安装：{}", manifest.id);
        }
        
        // 复制整个主题目录
        self.copy_dir_recursive(theme_path, &target_path)?;
        
        // 添加到已安装列表
        self.installed_themes.insert(manifest.id.clone(), manifest.clone());
        
        Ok(manifest.id.clone())
    }
    
    /// 卸载主题
    pub fn uninstall_theme(&mut self, theme_id: &str) -> Result<()> {
        // 不能卸载内置主题
        if theme_id.starts_with("com.readflow.theme.") {
            anyhow::bail!("无法卸载内置主题");
        }
        
        // 如果当前正在使用此主题，切换回默认主题
        if self.current_theme_id == theme_id {
            self.current_theme_id = "com.readflow.theme.dark".to_string();
        }
        
        // 从文件系统删除
        let theme_path = self.themes_dir.join(theme_id);
        if theme_path.exists() {
            std::fs::remove_dir_all(&theme_path)?;
        }
        
        // 从内存移除
        self.installed_themes.remove(theme_id);
        
        Ok(())
    }
    
    /// 自定义主题配置
    pub fn customize_theme(&mut self, theme_id: &str, config: ThemeConfig) -> Result<()> {
        self.configs.insert(theme_id.to_string(), config);
        Ok(())
    }
    
    /// 导出主题为 JSON
    pub fn export_theme(&self, theme_id: &str) -> Result<String> {
        let all_themes = self.get_all_themes();
        let theme = all_themes.iter()
            .find(|t| t.id == theme_id)
            .ok_or_else(|| anyhow::anyhow!("主题不存在：{}", theme_id))?;
        
        let json = serde_json::to_string_pretty(theme)?;
        Ok(json)
    }
    
    /// 递归复制目录
    fn copy_dir_recursive(&self, src: &Path, dst: &Path) -> Result<()> {
        std::fs::create_dir_all(dst)?;
        
        for entry in std::fs::read_dir(src)? {
            let entry = entry?;
            let src_path = entry.path();
            let dst_path = dst.join(entry.file_name());
            
            if src_path.is_dir() {
                self.copy_dir_recursive(&src_path, &dst_path)?;
            } else {
                std::fs::copy(&src_path, &dst_path)?;
            }
        }
        
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_builtin_themes() {
        let themes = BuiltinThemes::get_all();
        assert_eq!(themes.len(), 4);
        
        assert_eq!(themes[0].id, "com.readflow.theme.dark");
        assert_eq!(themes[1].id, "com.readflow.theme.light");
    }
    
    #[test]
    fn test_css_variables() {
        let dark_css = BuiltinThemes::get_css_variables("com.readflow.theme.dark");
        assert!(dark_css.contains("--bg-primary: #1a1a1a"));
        
        let light_css = BuiltinThemes::get_css_variables("com.readflow.theme.light");
        assert!(light_css.contains("--bg-primary: #ffffff"));
    }
}
