use crate::data::models::template::{
    TemplateSegmentWeight, CreateTemplateSegmentWeightRequest, UpdateTemplateSegmentWeightRequest,
    BatchUpdateTemplateSegmentWeightRequest
};
use crate::data::repositories::template_segment_weight_repository::TemplateSegmentWeightRepository;
use crate::data::repositories::ai_classification_repository::AiClassificationRepository;
use crate::business::services::template_segment_weight_service::TemplateSegmentWeightService;
use crate::business::services::ai_classification_service::AiClassificationService;
use crate::app_state::AppState;
use tauri::State;
use std::collections::HashMap;
use std::sync::Arc;

/// 创建模板片段权重服务实例的辅助函数
fn create_template_segment_weight_service(state: &AppState) -> TemplateSegmentWeightService {
    let database = state.get_database();
    let weight_repository = Arc::new(TemplateSegmentWeightRepository::new(database.clone()));
    let ai_classification_repository = Arc::new(AiClassificationRepository::new(database));
    let ai_classification_service = Arc::new(AiClassificationService::new(ai_classification_repository));
    TemplateSegmentWeightService::new(weight_repository, ai_classification_service)
}

/// 创建模板片段权重配置
#[tauri::command]
pub async fn create_template_segment_weight(
    state: State<'_, AppState>,
    request: CreateTemplateSegmentWeightRequest,
) -> Result<TemplateSegmentWeight, String> {
    let service = create_template_segment_weight_service(&state);

    service.create_weight_config(request)
        .await
        .map_err(|e| e.to_string())
}

/// 获取模板片段的权重配置（包含默认值）
#[tauri::command]
pub async fn get_segment_weights_with_defaults(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
) -> Result<HashMap<String, i32>, String> {
    let service = create_template_segment_weight_service(&state);

    service.get_segment_weights_with_defaults(&template_id, &track_segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 获取模板片段的AI分类按权重排序
#[tauri::command]
pub async fn get_classifications_by_segment_weight(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
) -> Result<Vec<crate::data::models::ai_classification::AiClassification>, String> {
    let service = create_template_segment_weight_service(&state);

    service.get_classifications_by_segment_weight(&template_id, &track_segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 批量更新模板片段权重配置
#[tauri::command]
pub async fn batch_update_template_segment_weights(
    state: State<'_, AppState>,
    request: BatchUpdateTemplateSegmentWeightRequest,
) -> Result<Vec<TemplateSegmentWeight>, String> {
    let service = create_template_segment_weight_service(&state);

    service.batch_update_weights(request)
        .await
        .map_err(|e| e.to_string())
}

/// 初始化模板片段的默认权重配置
#[tauri::command]
pub async fn initialize_default_segment_weights(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
) -> Result<Vec<TemplateSegmentWeight>, String> {
    let service = create_template_segment_weight_service(&state);
    
    service.initialize_default_weights(&template_id, &track_segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 重置模板片段权重配置为全局默认值
#[tauri::command]
pub async fn reset_segment_weights_to_global(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
) -> Result<Vec<TemplateSegmentWeight>, String> {
    let service = create_template_segment_weight_service(&state);
    
    service.reset_to_global_weights(&template_id, &track_segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 获取模板的所有权重配置
#[tauri::command]
pub async fn get_template_weights(
    state: State<'_, AppState>,
    template_id: String,
) -> Result<Vec<TemplateSegmentWeight>, String> {
    let service = create_template_segment_weight_service(&state);
    
    service.get_template_weights(&template_id)
        .await
        .map_err(|e| e.to_string())
}

/// 删除模板的所有权重配置
#[tauri::command]
pub async fn delete_template_weights(
    state: State<'_, AppState>,
    template_id: String,
) -> Result<usize, String> {
    let service = create_template_segment_weight_service(&state);

    service.delete_template_weights(&template_id)
        .await
        .map_err(|e| e.to_string())
}

/// 更新单个权重配置
#[tauri::command]
pub async fn update_template_segment_weight(
    state: State<'_, AppState>,
    id: String,
    request: UpdateTemplateSegmentWeightRequest,
) -> Result<Option<TemplateSegmentWeight>, String> {
    let service = create_template_segment_weight_service(&state);

    service.update_weight(&id, request)
        .await
        .map_err(|e| e.to_string())
}

/// 检查模板片段是否有自定义权重配置
#[tauri::command]
pub async fn has_custom_segment_weights(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
) -> Result<bool, String> {
    let service = create_template_segment_weight_service(&state);

    service.has_custom_weights(&template_id, &track_segment_id)
        .await
        .map_err(|e| e.to_string())
}

/// 获取权重配置的统计信息
#[tauri::command]
pub async fn get_template_weight_statistics(
    state: State<'_, AppState>,
    template_id: String,
) -> Result<HashMap<String, i32>, String> {
    let service = create_template_segment_weight_service(&state);

    service.get_weight_statistics(&template_id)
        .await
        .map_err(|e| e.to_string())
}

/// 获取指定分类的权重配置（用于按顺序匹配规则）
#[tauri::command]
pub async fn get_segment_weights_for_categories(
    state: State<'_, AppState>,
    template_id: String,
    track_segment_id: String,
    category_ids: Vec<String>,
) -> Result<HashMap<String, i32>, String> {
    let service = create_template_segment_weight_service(&state);

    service.get_segment_weights_for_categories(&template_id, &track_segment_id, &category_ids)
        .await
        .map_err(|e| e.to_string())
}
