use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

/// HSV颜色模型
/// 遵循 Tauri 开发规范的数据模型设计原则
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ColorHSV {
    /// 色相 (0-1)
    pub hue: f64,
    /// 饱和度 (0-1)
    pub saturation: f64,
    /// 明度 (0-1)
    pub value: f64,
}

impl ColorHSV {
    /// 创建新的HSV颜色
    pub fn new(hue: f64, saturation: f64, value: f64) -> Self {
        Self {
            hue: hue.clamp(0.0, 1.0),
            saturation: saturation.clamp(0.0, 1.0),
            value: value.clamp(0.0, 1.0),
        }
    }

    /// 从RGB十六进制字符串创建HSV颜色
    pub fn from_rgb_hex(hex: &str) -> Result<Self, String> {
        let hex = hex.trim_start_matches('#');
        if hex.len() != 6 {
            return Err("Invalid hex color format".to_string());
        }

        let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| "Invalid red component")?;
        let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| "Invalid green component")?;
        let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| "Invalid blue component")?;

        Ok(Self::from_rgb(r, g, b))
    }

    /// 从RGB值创建HSV颜色
    pub fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        let r = r as f64 / 255.0;
        let g = g as f64 / 255.0;
        let b = b as f64 / 255.0;

        let max = r.max(g).max(b);
        let min = r.min(g).min(b);
        let delta = max - min;

        let hue = if delta == 0.0 {
            0.0
        } else if max == r {
            ((g - b) / delta) % 6.0
        } else if max == g {
            (b - r) / delta + 2.0
        } else {
            (r - g) / delta + 4.0
        } / 6.0;

        let saturation = if max == 0.0 { 0.0 } else { delta / max };
        let value = max;

        Self::new(hue, saturation, value)
    }

    /// 转换为RGB十六进制字符串
    pub fn to_rgb_hex(&self) -> String {
        let (r, g, b) = self.to_rgb();
        format!("#{:02X}{:02X}{:02X}", r, g, b)
    }

    /// 转换为RGB值
    pub fn to_rgb(&self) -> (u8, u8, u8) {
        let c = self.value * self.saturation;
        let x = c * (1.0 - ((self.hue * 6.0) % 2.0 - 1.0).abs());
        let m = self.value - c;

        let (r_prime, g_prime, b_prime) = match (self.hue * 6.0) as i32 {
            0 => (c, x, 0.0),
            1 => (x, c, 0.0),
            2 => (0.0, c, x),
            3 => (0.0, x, c),
            4 => (x, 0.0, c),
            _ => (c, 0.0, x),
        };

        let r = ((r_prime + m) * 255.0) as u8;
        let g = ((g_prime + m) * 255.0) as u8;
        let b = ((b_prime + m) * 255.0) as u8;

        (r, g, b)
    }

    /// 计算与另一个颜色的距离
    pub fn distance(&self, other: &ColorHSV) -> f64 {
        // 色相环形距离计算
        let hue_diff = (self.hue - other.hue).abs();
        let hue_distance = hue_diff.min(1.0 - hue_diff);
        
        // 饱和度和明度线性距离
        let sat_distance = (self.saturation - other.saturation).abs();
        let val_distance = (self.value - other.value).abs();
        
        // 加权距离计算：色相50%，饱和度30%，明度20%
        hue_distance * 0.5 + sat_distance * 0.3 + val_distance * 0.2
    }

    /// 计算颜色相似度 (0-1，1表示完全相同)
    pub fn similarity(&self, other: &ColorHSV) -> f64 {
        1.0 - self.distance(other)
    }

    /// 判断颜色是否在指定阈值范围内匹配
    pub fn matches(&self, other: &ColorHSV, hue_threshold: f64, sat_threshold: f64, val_threshold: f64) -> bool {
        let hue_diff = (self.hue - other.hue).abs().min(1.0 - (self.hue - other.hue).abs());
        let sat_diff = (self.saturation - other.saturation).abs();
        let val_diff = (self.value - other.value).abs();
        
        hue_diff <= hue_threshold && sat_diff <= sat_threshold && val_diff <= val_threshold
    }
}

/// 服装产品分析结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductAnalysis {
    /// 服装类别
    pub category: String,
    /// 服装描述
    pub description: String,
    /// 主要颜色
    pub color_pattern: ColorHSV,
    /// 设计风格标签
    pub design_styles: Vec<String>,
    /// 与整体搭配的颜色匹配度 (0-1)
    pub color_pattern_match_dress: f64,
    /// 与环境的颜色匹配度 (0-1)
    pub color_pattern_match_environment: f64,
}

/// Gemini AI分析结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutfitAnalysisResult {
    /// 环境标签
    pub environment_tags: Vec<String>,
    /// 环境主色调
    pub environment_color_pattern: ColorHSV,
    /// 整体搭配主色调
    pub dress_color_pattern: ColorHSV,
    /// 风格描述
    pub style_description: String,
    /// 识别的服装产品列表
    pub products: Vec<ProductAnalysis>,
}

/// 图像分析请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyzeImageRequest {
    /// 图像文件路径
    pub image_path: String,
    /// 图像文件名
    pub image_name: String,
}

/// 图像分析响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyzeImageResponse {
    /// 分析结果（JSON格式）
    pub result: serde_json::Value,
    /// 分析耗时（毫秒）
    pub analysis_time_ms: u64,
    /// 分析时间戳
    pub analyzed_at: DateTime<Utc>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_color_hsv_creation() {
        let color = ColorHSV::new(0.5, 0.8, 0.9);
        assert_eq!(color.hue, 0.5);
        assert_eq!(color.saturation, 0.8);
        assert_eq!(color.value, 0.9);
    }

    #[test]
    fn test_color_hsv_clamping() {
        // 测试值被正确限制在0-1范围内
        let color = ColorHSV::new(1.5, -0.2, 2.0);
        assert_eq!(color.hue, 1.0);
        assert_eq!(color.saturation, 0.0);
        assert_eq!(color.value, 1.0);
    }

    #[test]
    fn test_color_hsv_from_rgb_hex() {
        // 测试红色
        let red = ColorHSV::from_rgb_hex("#FF0000").unwrap();
        assert!((red.hue - 0.0).abs() < 0.01);
        assert!((red.saturation - 1.0).abs() < 0.01);
        assert!((red.value - 1.0).abs() < 0.01);

        // 测试绿色
        let green = ColorHSV::from_rgb_hex("#00FF00").unwrap();
        assert!((green.hue - 0.333).abs() < 0.01);
        assert!((green.saturation - 1.0).abs() < 0.01);
        assert!((green.value - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_color_hsv_from_rgb_hex_invalid() {
        // 测试无效的十六进制格式
        assert!(ColorHSV::from_rgb_hex("#FF").is_err());
        assert!(ColorHSV::from_rgb_hex("#GGGGGG").is_err());
    }

    #[test]
    fn test_color_hsv_to_rgb_hex() {
        let color = ColorHSV::new(0.0, 1.0, 1.0); // 纯红色
        assert_eq!(color.to_rgb_hex(), "#FF0000");

        let white = ColorHSV::new(0.0, 0.0, 1.0);
        assert_eq!(white.to_rgb_hex(), "#FFFFFF");

        let black = ColorHSV::new(0.0, 0.0, 0.0);
        assert_eq!(black.to_rgb_hex(), "#000000");
    }

    #[test]
    fn test_color_distance() {
        // 测试相同颜色的距离
        let color1 = ColorHSV::new(0.5, 0.8, 0.9);
        let color2 = ColorHSV::new(0.5, 0.8, 0.9);
        assert_eq!(color1.distance(&color2), 0.0);

        // 测试不同颜色的距离
        let red = ColorHSV::new(0.0, 1.0, 1.0);
        let blue = ColorHSV::new(0.67, 1.0, 1.0);
        let distance = red.distance(&blue);
        assert!(distance > 0.0);
        assert!(distance <= 1.0);
    }

    #[test]
    fn test_color_similarity() {
        let color1 = ColorHSV::new(0.5, 0.8, 0.9);
        let color2 = ColorHSV::new(0.5, 0.8, 0.9);
        assert_eq!(color1.similarity(&color2), 1.0);
    }

    #[test]
    fn test_color_matches() {
        let base_color = ColorHSV::new(0.5, 0.8, 0.9);
        let similar_color = ColorHSV::new(0.51, 0.81, 0.91);
        assert!(base_color.matches(&similar_color, 0.05, 0.05, 0.05));

        let different_color = ColorHSV::new(0.6, 0.9, 1.0);
        assert!(!base_color.matches(&different_color, 0.05, 0.05, 0.05));
    }
}
