use crate::app_state::AppState;
use crate::business::services::ai_analysis_log_service::{
    AiAnalysisLogService, AiAnalysisLogQuery, AiAnalysisLogResponse, AiAnalysisLogStats
};
use crate::data::repositories::video_classification_repository::VideoClassificationRepository;
use std::sync::Arc;
use tauri::State;

/// 获取AI分析日志
/// 
/// 遵循 Tauri 开发规范的命令设计原则：
/// - 输入验证和错误处理
/// - 异步处理和性能优化
/// - 安全的数据访问控制
#[tauri::command]
pub async fn get_ai_analysis_logs(
    query: AiAnalysisLogQuery,
    state: State<'_, AppState>,
) -> Result<AiAnalysisLogResponse, String> {
    // 输入验证
    if query.project_id.is_empty() {
        return Err("项目ID不能为空".to_string());
    }

    if query.page == 0 {
        return Err("页码必须大于0".to_string());
    }

    if query.page_size == 0 || query.page_size > 100 {
        return Err("每页大小必须在1-100之间".to_string());
    }

    if !["records", "tasks"].contains(&query.log_type.as_str()) {
        return Err("日志类型必须是records或tasks".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();
    
    // 创建仓库和服务实例
    let video_repo = Arc::new(VideoClassificationRepository::new(database));
    let log_service = AiAnalysisLogService::new(video_repo);

    // 执行查询
    match log_service.get_analysis_logs(query).await {
        Ok(response) => Ok(response),
        Err(e) => {
            eprintln!("获取AI分析日志失败: {}", e);
            Err(format!("获取AI分析日志失败: {}", e))
        }
    }
}

/// 获取AI分析统计信息
/// 
/// 提供项目的AI分析概览数据
#[tauri::command]
pub async fn get_ai_analysis_stats(
    project_id: String,
    state: State<'_, AppState>,
) -> Result<AiAnalysisLogStats, String> {
    // 输入验证
    if project_id.is_empty() {
        return Err("项目ID不能为空".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();
    
    // 创建仓库和服务实例
    let video_repo = Arc::new(VideoClassificationRepository::new(database));
    let log_service = AiAnalysisLogService::new(video_repo);

    // 执行查询
    match log_service.get_analysis_stats(&project_id).await {
        Ok(stats) => Ok(stats),
        Err(e) => {
            eprintln!("获取AI分析统计失败: {}", e);
            Err(format!("获取AI分析统计失败: {}", e))
        }
    }
}

/// 导出AI分析日志
/// 
/// 支持CSV和JSON格式的日志导出
#[tauri::command]
pub async fn export_ai_analysis_logs(
    project_id: String,
    format: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    // 输入验证
    if project_id.is_empty() {
        return Err("项目ID不能为空".to_string());
    }

    if !["csv", "json"].contains(&format.as_str()) {
        return Err("导出格式必须是csv或json".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();
    
    // 创建仓库和服务实例
    let video_repo = Arc::new(VideoClassificationRepository::new(database));
    let log_service = AiAnalysisLogService::new(video_repo);

    // 执行导出
    match log_service.export_analysis_logs(&project_id, &format).await {
        Ok(result) => Ok(result),
        Err(e) => {
            eprintln!("导出AI分析日志失败: {}", e);
            Err(format!("导出AI分析日志失败: {}", e))
        }
    }
}

/// 清理过期的AI分析日志
/// 
/// 删除指定天数之前的日志记录，释放存储空间
#[tauri::command]
pub async fn cleanup_ai_analysis_logs(
    project_id: String,
    days_to_keep: u32,
    _state: State<'_, AppState>,
) -> Result<u64, String> {
    // 输入验证
    if project_id.is_empty() {
        return Err("项目ID不能为空".to_string());
    }

    if days_to_keep == 0 {
        return Err("保留天数必须大于0".to_string());
    }

    if days_to_keep > 365 {
        return Err("保留天数不能超过365天".to_string());
    }

    // TODO: 实现日志清理功能
    // 这里应该调用仓库层的清理方法
    
    // 暂时返回模拟结果
    Ok(0)
}

/// 重试失败的分类任务
/// 
/// 重新启动失败的AI分类任务
#[tauri::command]
pub async fn retry_failed_classification_task(
    task_id: String,
    state: State<'_, AppState>,
) -> Result<(), String> {
    // 输入验证
    if task_id.is_empty() {
        return Err("任务ID不能为空".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();
    
    // 创建仓库实例
    let video_repo = Arc::new(VideoClassificationRepository::new(database));

    // 获取任务信息
    match video_repo.get_classification_task_by_id(&task_id).await {
        Ok(Some(mut task)) => {
            // 检查任务是否可以重试
            if !task.can_retry() {
                return Err("任务已达到最大重试次数或状态不允许重试".to_string());
            }

            // 重置任务状态
            task.reset_for_retry();
            
            // 更新任务
            match video_repo.update_classification_task(&task).await {
                Ok(_) => {
                    println!("任务 {} 已重置为等待状态，将在队列中重新处理", task_id);
                    Ok(())
                }
                Err(e) => {
                    eprintln!("更新任务状态失败: {}", e);
                    Err(format!("更新任务状态失败: {}", e))
                }
            }
        }
        Ok(None) => Err("未找到指定的任务".to_string()),
        Err(e) => {
            eprintln!("获取任务信息失败: {}", e);
            Err(format!("获取任务信息失败: {}", e))
        }
    }
}

/// 获取分类记录详情
/// 
/// 获取单个分类记录的详细信息
#[tauri::command]
pub async fn get_classification_record_detail(
    record_id: String,
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    // 输入验证
    if record_id.is_empty() {
        return Err("记录ID不能为空".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();
    
    // 创建仓库实例
    let _video_repo = Arc::new(VideoClassificationRepository::new(database));

    // 查询记录详情
    // TODO: 实现根据ID查询单个记录的方法
    
    // 暂时返回模拟数据
    let detail = serde_json::json!({
        "id": record_id,
        "message": "记录详情功能待实现"
    });

    Ok(detail)
}

/// 批量删除分类记录
/// 
/// 删除选中的分类记录
#[tauri::command]
pub async fn delete_classification_records(
    record_ids: Vec<String>,
    _state: State<'_, AppState>,
) -> Result<u64, String> {
    // 输入验证
    if record_ids.is_empty() {
        return Err("记录ID列表不能为空".to_string());
    }

    if record_ids.len() > 100 {
        return Err("一次最多只能删除100条记录".to_string());
    }

    // 验证所有ID都不为空
    for id in &record_ids {
        if id.is_empty() {
            return Err("记录ID不能为空".to_string());
        }
    }

    // TODO: 实现批量删除功能
    // 这里应该调用仓库层的批量删除方法
    
    // 暂时返回模拟结果
    Ok(record_ids.len() as u64)
}

/// 获取AI分析日志的可用过滤选项
/// 
/// 返回状态、类型等过滤选项
#[tauri::command]
pub async fn get_ai_analysis_log_filters() -> Result<serde_json::Value, String> {
    let filters = serde_json::json!({
        "log_types": [
            {"value": "records", "label": "分类记录"},
            {"value": "tasks", "label": "分类任务"}
        ],
        "record_statuses": [
            {"value": "Classified", "label": "分类成功"},
            {"value": "Failed", "label": "分类失败"},
            {"value": "NeedsReview", "label": "需要审核"}
        ],
        "task_statuses": [
            {"value": "Pending", "label": "等待处理"},
            {"value": "Uploading", "label": "上传中"},
            {"value": "Analyzing", "label": "分析中"},
            {"value": "Completed", "label": "已完成"},
            {"value": "Failed", "label": "处理失败"},
            {"value": "Cancelled", "label": "已取消"}
        ],
        "export_formats": [
            {"value": "csv", "label": "CSV格式"},
            {"value": "json", "label": "JSON格式"}
        ]
    });

    Ok(filters)
}

/// 创建测试AI分析日志数据
///
/// 仅用于开发测试，创建一些示例数据
#[tauri::command]
pub async fn create_test_ai_analysis_logs(
    project_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    use crate::data::models::video_classification::*;
    use chrono::Utc;
    use uuid::Uuid;

    // 输入验证
    if project_id.is_empty() {
        return Err("项目ID不能为空".to_string());
    }

    // 获取数据库连接
    let database = state.get_database();

    // 创建仓库实例
    let video_repo = Arc::new(VideoClassificationRepository::new(database));

    // 创建测试分类记录
    let test_records = vec![
        VideoClassificationRecord {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            category: "全身".to_string(),
            confidence: 0.85,
            reasoning: "视频显示完整的人体轮廓，动作清晰可见".to_string(),
            features: vec!["全身动作".to_string(), "清晰画质".to_string()],
            product_match: true,
            quality_score: 0.9,
            gemini_file_uri: Some("gs://test-bucket/video1.mp4".to_string()),
            raw_response: Some("{\"category\":\"全身\",\"confidence\":0.85}".to_string()),
            status: ClassificationStatus::Classified,
            error_message: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
        VideoClassificationRecord {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            category: "半身".to_string(),
            confidence: 0.72,
            reasoning: "视频主要显示上半身，部分下肢不可见".to_string(),
            features: vec!["上半身".to_string(), "中等画质".to_string()],
            product_match: false,
            quality_score: 0.7,
            gemini_file_uri: Some("gs://test-bucket/video2.mp4".to_string()),
            raw_response: Some("{\"category\":\"半身\",\"confidence\":0.72}".to_string()),
            status: ClassificationStatus::NeedsReview,
            error_message: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
        VideoClassificationRecord {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            category: "未分类".to_string(),
            confidence: 0.3,
            reasoning: "视频质量较差，无法准确识别".to_string(),
            features: vec!["模糊画质".to_string()],
            product_match: false,
            quality_score: 0.3,
            gemini_file_uri: Some("gs://test-bucket/video3.mp4".to_string()),
            raw_response: Some("{\"error\":\"分析失败\"}".to_string()),
            status: ClassificationStatus::Failed,
            error_message: Some("视频质量过低，无法进行有效分析".to_string()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
    ];

    // 创建测试任务记录
    let test_tasks = vec![
        VideoClassificationTask {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            video_file_path: "/test/videos/sample1.mp4".to_string(),
            status: TaskStatus::Completed,
            priority: 1,
            retry_count: 0,
            max_retries: 3,
            gemini_file_uri: Some("gs://test-bucket/video1.mp4".to_string()),
            prompt_text: Some("请分析这个视频的内容".to_string()),
            error_message: None,
            started_at: Some(Utc::now()),
            completed_at: Some(Utc::now()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
        VideoClassificationTask {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            video_file_path: "/test/videos/sample2.mp4".to_string(),
            status: TaskStatus::Failed,
            priority: 1,
            retry_count: 2,
            max_retries: 3,
            gemini_file_uri: None,
            prompt_text: Some("请分析这个视频的内容".to_string()),
            error_message: Some("网络连接超时".to_string()),
            started_at: Some(Utc::now()),
            completed_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
        VideoClassificationTask {
            id: Uuid::new_v4().to_string(),
            segment_id: format!("segment_{}", Uuid::new_v4()),
            material_id: format!("material_{}", Uuid::new_v4()),
            project_id: project_id.clone(),
            video_file_path: "/test/videos/sample3.mp4".to_string(),
            status: TaskStatus::Analyzing,
            priority: 1,
            retry_count: 0,
            max_retries: 3,
            gemini_file_uri: Some("gs://test-bucket/video3.mp4".to_string()),
            prompt_text: Some("请分析这个视频的内容".to_string()),
            error_message: None,
            started_at: Some(Utc::now()),
            completed_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        },
    ];

    // 保存测试数据
    let mut created_count = 0;

    for record in test_records {
        match video_repo.create_classification_record(record).await {
            Ok(_) => created_count += 1,
            Err(e) => eprintln!("创建测试记录失败: {}", e),
        }
    }

    for task in test_tasks {
        match video_repo.create_classification_task(task).await {
            Ok(_) => created_count += 1,
            Err(e) => eprintln!("创建测试任务失败: {}", e),
        }
    }

    Ok(format!("成功创建 {} 条测试数据", created_count))
}
