use crate::data::models::template::{
    TemplateSegmentWeight, CreateTemplateSegmentWeightRequest, UpdateTemplateSegmentWeightRequest,
    BatchUpdateTemplateSegmentWeightRequest, SegmentWeightConfig
};
use crate::data::models::ai_classification::AiClassification;
use crate::data::repositories::template_segment_weight_repository::TemplateSegmentWeightRepository;
use crate::business::services::ai_classification_service::AiClassificationService;
use anyhow::Result;
use std::collections::HashMap;
use std::sync::Arc;

/// 模板片段权重配置服务
/// 遵循 Tauri 开发规范的服务层设计原则
pub struct TemplateSegmentWeightService {
    repository: Arc<TemplateSegmentWeightRepository>,
    ai_classification_service: Arc<AiClassificationService>,
}

impl TemplateSegmentWeightService {
    /// 创建新的服务实例
    pub fn new(
        repository: Arc<TemplateSegmentWeightRepository>,
        ai_classification_service: Arc<AiClassificationService>,
    ) -> Self {
        Self {
            repository,
            ai_classification_service,
        }
    }

    /// 创建模板片段权重配置
    pub async fn create_weight_config(&self, request: CreateTemplateSegmentWeightRequest) -> Result<TemplateSegmentWeight> {
        // 验证权重值
        TemplateSegmentWeight::validate_weight(request.weight)
            .map_err(|e| anyhow::anyhow!(e))?;

        // 验证AI分类是否存在
        if self.ai_classification_service.get_classification_by_id(&request.ai_classification_id).await?.is_none() {
            return Err(anyhow::anyhow!("AI分类不存在"));
        }

        self.repository.create(request).await
    }

    /// 获取模板片段的权重配置，如果不存在则使用全局权重作为默认值
    pub async fn get_segment_weights_with_defaults(&self, template_id: &str, track_segment_id: &str) -> Result<HashMap<String, i32>> {
        // 获取模板片段的自定义权重配置
        let custom_weights = self.repository.get_weight_map_for_segment(template_id, track_segment_id).await?;

        // 获取所有激活的AI分类
        let ai_classifications = self.ai_classification_service.get_classifications_by_weight().await?;

        let mut final_weights = HashMap::new();

        // 为每个AI分类设置权重（优先使用自定义权重，否则使用全局权重）
        for classification in ai_classifications {
            let weight = custom_weights.get(&classification.id)
                .copied()
                .unwrap_or(classification.weight); // 使用全局权重作为默认值
            
            final_weights.insert(classification.id, weight);
        }

        Ok(final_weights)
    }

    /// 获取模板片段的AI分类按权重排序（考虑自定义权重）
    pub async fn get_classifications_by_segment_weight(&self, template_id: &str, track_segment_id: &str) -> Result<Vec<AiClassification>> {
        // 获取权重映射
        let weight_map = self.get_segment_weights_with_defaults(template_id, track_segment_id).await?;

        // 获取所有激活的AI分类
        let mut ai_classifications = self.ai_classification_service.get_classifications_by_weight().await?;

        // 根据模板片段的权重配置重新排序
        ai_classifications.sort_by(|a, b| {
            let weight_a = weight_map.get(&a.id).copied().unwrap_or(a.weight);
            let weight_b = weight_map.get(&b.id).copied().unwrap_or(b.weight);
            weight_b.cmp(&weight_a) // 降序排列
        });

        Ok(ai_classifications)
    }

    /// 批量更新模板片段权重配置
    pub async fn batch_update_weights(&self, request: BatchUpdateTemplateSegmentWeightRequest) -> Result<Vec<TemplateSegmentWeight>> {
        // 验证所有权重值
        for weight_config in &request.weights {
            TemplateSegmentWeight::validate_weight(weight_config.weight)
                .map_err(|e| anyhow::anyhow!(e))?;
        }

        // 验证所有AI分类是否存在
        for weight_config in &request.weights {
            if self.ai_classification_service.get_classification_by_id(&weight_config.ai_classification_id).await?.is_none() {
                return Err(anyhow::anyhow!("AI分类 {} 不存在", weight_config.ai_classification_id));
            }
        }

        self.repository.batch_update(request).await
    }

    /// 初始化模板片段的默认权重配置（使用全局权重）
    pub async fn initialize_default_weights(&self, template_id: &str, track_segment_id: &str) -> Result<Vec<TemplateSegmentWeight>> {
        // 检查是否已有配置
        let existing_weights = self.repository.get_by_template_and_segment(template_id, track_segment_id).await?;

        if !existing_weights.is_empty() {
            return Ok(existing_weights);
        }

        // 获取所有激活的AI分类
        let ai_classifications = self.ai_classification_service.get_classifications_by_weight().await?;

        // 创建默认权重配置
        let weight_configs: Vec<SegmentWeightConfig> = ai_classifications
            .into_iter()
            .map(|classification| SegmentWeightConfig {
                ai_classification_id: classification.id,
                weight: classification.weight, // 使用全局权重作为默认值
            })
            .collect();

        let batch_request = BatchUpdateTemplateSegmentWeightRequest {
            template_id: template_id.to_string(),
            track_segment_id: track_segment_id.to_string(),
            weights: weight_configs,
        };

        self.batch_update_weights(batch_request).await
    }

    /// 重置模板片段权重配置为全局默认值
    pub async fn reset_to_global_weights(&self, template_id: &str, track_segment_id: &str) -> Result<Vec<TemplateSegmentWeight>> {
        // 删除现有配置
        self.repository.delete_by_template_id(template_id).await?;

        // 重新初始化为默认值
        self.initialize_default_weights(template_id, track_segment_id).await
    }

    /// 获取模板的所有权重配置
    pub async fn get_template_weights(&self, template_id: &str) -> Result<Vec<TemplateSegmentWeight>> {
        self.repository.get_by_template_id(template_id).await
    }

    /// 删除模板的所有权重配置
    pub async fn delete_template_weights(&self, template_id: &str) -> Result<usize> {
        self.repository.delete_by_template_id(template_id).await
    }

    /// 更新单个权重配置
    pub async fn update_weight(&self, id: &str, request: UpdateTemplateSegmentWeightRequest) -> Result<Option<TemplateSegmentWeight>> {
        // 验证权重值
        TemplateSegmentWeight::validate_weight(request.weight)
            .map_err(|e| anyhow::anyhow!(e))?;

        self.repository.update(id, request).await
    }

    /// 检查模板片段是否有自定义权重配置
    pub async fn has_custom_weights(&self, template_id: &str, track_segment_id: &str) -> Result<bool> {
        let weights = self.repository.get_by_template_and_segment(template_id, track_segment_id).await?;
        
        Ok(!weights.is_empty())
    }

    /// 获取权重配置的统计信息
    pub async fn get_weight_statistics(&self, template_id: &str) -> Result<HashMap<String, i32>> {
        let weights = self.get_template_weights(template_id).await?;

        let mut stats = HashMap::new();
        stats.insert("total_configurations".to_string(), weights.len() as i32);

        // 统计每个AI分类的配置数量
        let mut classification_counts = HashMap::new();
        for weight in weights {
            *classification_counts.entry(weight.ai_classification_id).or_insert(0) += 1;
        }

        stats.insert("unique_classifications".to_string(), classification_counts.len() as i32);

        Ok(stats)
    }

    /// 获取指定分类的权重配置（用于按顺序匹配规则）
    pub async fn get_segment_weights_for_categories(&self, template_id: &str, track_segment_id: &str, category_ids: &[String]) -> Result<HashMap<String, i32>> {
        // 获取模板片段的自定义权重配置
        let custom_weights = self.repository.get_weight_map_for_segment(template_id, track_segment_id).await?;

        // 获取指定分类的AI分类信息
        let mut final_weights = HashMap::new();

        for category_id in category_ids {
            // 优先使用自定义权重
            if let Some(&custom_weight) = custom_weights.get(category_id) {
                final_weights.insert(category_id.clone(), custom_weight);
            } else {
                // 如果没有自定义权重，获取全局权重
                if let Ok(Some(classification)) = self.ai_classification_service.get_classification_by_id(category_id).await {
                    final_weights.insert(category_id.clone(), classification.weight);
                } else {
                    // 如果分类不存在，使用默认权重
                    final_weights.insert(category_id.clone(), 50);
                }
            }
        }

        Ok(final_weights)
    }
}
