use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use crate::data::models::outfit_search::{SearchConfig, SearchResult, ProductInfo};
use crate::data::models::outfit_recommendation::OutfitRecommendation;

/// 素材检索请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialSearchRequest {
    /// 基于穿搭方案生成的搜索查询
    pub query: String,
    /// 穿搭方案ID
    pub recommendation_id: String,
    /// 搜索配置
    pub search_config: MaterialSearchConfig,
    /// 分页信息
    pub pagination: MaterialSearchPagination,
}

/// 素材检索分页信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialSearchPagination {
    /// 当前页码（从1开始）
    pub page: u32,
    /// 每页大小
    pub page_size: u32,
}

impl Default for MaterialSearchPagination {
    fn default() -> Self {
        Self {
            page: 1,
            page_size: 9,
        }
    }
}

/// 素材检索配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialSearchConfig {
    /// 相关性阈值
    pub relevance_threshold: String, // "LOWEST" | "LOW" | "MEDIUM" | "HIGH"
    /// 类别过滤
    pub categories: Vec<String>,
    /// 环境标签
    pub environments: Vec<String>,
    /// 颜色过滤器
    pub color_filters: std::collections::HashMap<String, MaterialColorFilter>,
    /// 设计风格
    pub design_styles: std::collections::HashMap<String, Vec<String>>,
    /// 最大结果数量
    pub max_results: u32,
}

impl Default for MaterialSearchConfig {
    fn default() -> Self {
        Self {
            relevance_threshold: "HIGH".to_string(),
            categories: Vec::new(),
            environments: Vec::new(),
            color_filters: std::collections::HashMap::new(),
            design_styles: std::collections::HashMap::new(),
            max_results: 50,
        }
    }
}

/// 素材颜色过滤器
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialColorFilter {
    /// 是否启用
    pub enabled: bool,
    /// 目标颜色
    pub color: MaterialColorHSV,
    /// 色相阈值
    pub hue_threshold: f64,
    /// 饱和度阈值
    pub saturation_threshold: f64,
    /// 明度阈值
    pub value_threshold: f64,
}

impl Default for MaterialColorFilter {
    fn default() -> Self {
        Self {
            enabled: false,
            color: MaterialColorHSV::default(),
            hue_threshold: 0.05,
            saturation_threshold: 0.05,
            value_threshold: 0.20,
        }
    }
}

/// 素材颜色HSV表示
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialColorHSV {
    /// 色相 (0-1)
    pub hue: f64,
    /// 饱和度 (0-1)
    pub saturation: f64,
    /// 明度 (0-1)
    pub value: f64,
}

impl Default for MaterialColorHSV {
    fn default() -> Self {
        Self {
            hue: 0.0,
            saturation: 0.0,
            value: 0.0,
        }
    }
}

/// 素材检索结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialSearchResult {
    /// 结果ID
    pub id: String,
    /// 图片URL
    pub image_url: String,
    /// 风格描述
    pub style_description: String,
    /// 环境标签
    pub environment_tags: Vec<String>,
    /// 产品信息
    pub products: Vec<MaterialProduct>,
    /// 相关性评分
    pub relevance_score: f64,
    /// 创建时间
    pub created_at: DateTime<Utc>,
}

/// 素材产品信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialProduct {
    /// 产品类别
    pub category: String,
    /// 产品描述
    pub description: String,
    /// 主要颜色
    pub color_pattern: MaterialColorHSV,
    /// 设计风格
    pub design_styles: Vec<String>,
}

/// 素材检索响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialSearchResponse {
    /// 搜索结果列表
    pub results: Vec<MaterialSearchResult>,
    /// 总结果数量
    pub total_size: u32,
    /// 当前页码
    pub current_page: u32,
    /// 每页大小
    pub page_size: u32,
    /// 总页数
    pub total_pages: u32,
    /// 搜索耗时（毫秒）
    pub search_time_ms: u64,
    /// 搜索时间戳
    pub searched_at: DateTime<Utc>,
    /// 下一页令牌
    pub next_page_token: Option<String>,
}

/// 智能检索条件生成请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerateSearchQueryRequest {
    /// 穿搭方案
    pub recommendation: OutfitRecommendation,
    /// 生成选项
    pub options: Option<GenerateSearchQueryOptions>,
}

/// 智能检索条件生成选项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerateSearchQueryOptions {
    /// 是否包含颜色信息
    pub include_colors: Option<bool>,
    /// 是否包含风格信息
    pub include_styles: Option<bool>,
    /// 是否包含场合信息
    pub include_occasions: Option<bool>,
    /// 是否包含季节信息
    pub include_seasons: Option<bool>,
}

impl Default for GenerateSearchQueryOptions {
    fn default() -> Self {
        Self {
            include_colors: Some(true),
            include_styles: Some(true),
            include_occasions: Some(true),
            include_seasons: Some(false), // 季节信息可能不太相关
        }
    }
}

/// 智能检索条件生成响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerateSearchQueryResponse {
    /// 生成的搜索查询
    pub query: String,
    /// 生成的搜索配置
    pub search_config: MaterialSearchConfig,
    /// 生成时间（毫秒）
    pub generation_time_ms: u64,
    /// 生成时间戳
    pub generated_at: DateTime<Utc>,
}

// 实现从现有类型的转换
impl From<SearchResult> for MaterialSearchResult {
    fn from(search_result: SearchResult) -> Self {
        Self {
            id: search_result.id,
            image_url: search_result.image_url,
            style_description: search_result.style_description,
            environment_tags: search_result.environment_tags,
            products: search_result.products.into_iter().map(MaterialProduct::from).collect(),
            relevance_score: search_result.relevance_score,
            created_at: Utc::now(),
        }
    }
}

impl From<ProductInfo> for MaterialProduct {
    fn from(product_info: ProductInfo) -> Self {
        Self {
            category: product_info.category,
            description: product_info.description,
            color_pattern: MaterialColorHSV {
                hue: product_info.color_pattern.hue,
                saturation: product_info.color_pattern.saturation,
                value: product_info.color_pattern.value,
            },
            design_styles: product_info.design_styles,
        }
    }
}

impl From<MaterialSearchConfig> for SearchConfig {
    fn from(material_config: MaterialSearchConfig) -> Self {
        use crate::data::models::outfit_search::{RelevanceThreshold, ColorFilter};
        use crate::data::models::gemini_analysis::ColorHSV;
        use std::collections::HashMap;

        let relevance_threshold = match material_config.relevance_threshold.as_str() {
            "LOWEST" => RelevanceThreshold::Lowest,
            "LOW" => RelevanceThreshold::Low,
            "MEDIUM" => RelevanceThreshold::Medium,
            "HIGH" => RelevanceThreshold::High,
            _ => RelevanceThreshold::High,
        };

        let mut color_filters = HashMap::new();
        for (category, material_filter) in material_config.color_filters {
            let color_filter = ColorFilter {
                enabled: material_filter.enabled,
                color: ColorHSV::new(
                    material_filter.color.hue,
                    material_filter.color.saturation,
                    material_filter.color.value,
                ),
                hue_threshold: material_filter.hue_threshold,
                saturation_threshold: material_filter.saturation_threshold,
                value_threshold: material_filter.value_threshold,
            };
            color_filters.insert(category, color_filter);
        }

        Self {
            relevance_threshold,
            environments: material_config.environments,
            categories: material_config.categories,
            color_filters,
            design_styles: material_config.design_styles,
            max_keywords: 10,
            debug_mode: false,
            custom_filters: Vec::new(),
            query_enhancement_enabled: true,
            color_thresholds: Default::default(),
        }
    }
}
