use crate::data::models::video_classification::*;
use crate::data::repositories::video_classification_repository::VideoClassificationRepository;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use chrono::{DateTime, Utc};

/// AI分析日志查询参数
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiAnalysisLogQuery {
    /// 项目ID
    pub project_id: String,
    /// 日志类型（records或tasks）
    pub log_type: String,
    /// 状态过滤
    pub status_filter: Option<String>,
    /// 搜索关键词
    pub search_keyword: Option<String>,
    /// 页码（从1开始）
    pub page: u32,
    /// 每页大小
    pub page_size: u32,
}

impl Default for AiAnalysisLogQuery {
    fn default() -> Self {
        Self {
            project_id: String::new(),
            log_type: "records".to_string(),
            status_filter: None,
            search_keyword: None,
            page: 1,
            page_size: 20,
        }
    }
}

/// AI分析日志响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiAnalysisLogResponse {
    /// 日志数据
    pub logs: Vec<AiAnalysisLogItem>,
    /// 总数
    pub total_count: u64,
    /// 当前页
    pub current_page: u32,
    /// 每页大小
    pub page_size: u32,
    /// 总页数
    pub total_pages: u32,
}

/// AI分析日志项
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiAnalysisLogItem {
    /// 日志ID
    pub id: String,
    /// 日志类型
    pub log_type: String,
    /// 标题
    pub title: String,
    /// 状态
    pub status: String,
    /// 状态显示名称
    pub status_display: String,
    /// 详细信息
    pub details: String,
    /// 错误信息
    pub error_message: Option<String>,
    /// 置信度（仅分类记录）
    pub confidence: Option<f64>,
    /// 质量评分（仅分类记录）
    pub quality_score: Option<f64>,
    /// 分类结果（仅分类记录）
    pub category: Option<String>,
    /// 视频文件路径（仅任务记录）
    pub video_file_path: Option<String>,
    /// 重试次数（仅任务记录）
    pub retry_count: Option<i32>,
    /// 创建时间
    pub created_at: DateTime<Utc>,
    /// 更新时间
    pub updated_at: DateTime<Utc>,
}

/// AI分析日志统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiAnalysisLogStats {
    /// 总记录数
    pub total_records: u64,
    /// 成功分类数
    pub successful_classifications: u64,
    /// 失败分类数
    pub failed_classifications: u64,
    /// 需要审核数
    pub needs_review: u64,
    /// 总任务数
    pub total_tasks: u64,
    /// 完成任务数
    pub completed_tasks: u64,
    /// 失败任务数
    pub failed_tasks: u64,
    /// 处理中任务数
    pub processing_tasks: u64,
    /// 平均置信度
    pub average_confidence: f64,
    /// 平均质量评分
    pub average_quality_score: f64,
    /// 最近24小时活动数
    pub recent_24h_activity: u64,
}

/// AI分析日志服务
/// 遵循 Tauri 开发规范的业务逻辑层设计模式
pub struct AiAnalysisLogService {
    video_repo: Arc<VideoClassificationRepository>,
}

impl AiAnalysisLogService {
    /// 创建新的AI分析日志服务实例
    pub fn new(video_repo: Arc<VideoClassificationRepository>) -> Self {
        Self { video_repo }
    }

    /// 获取AI分析日志
    pub async fn get_analysis_logs(&self, query: AiAnalysisLogQuery) -> Result<AiAnalysisLogResponse> {
        let logs = match query.log_type.as_str() {
            "records" => self.get_classification_records(&query).await?,
            "tasks" => self.get_classification_tasks(&query).await?,
            _ => return Err(anyhow::anyhow!("不支持的日志类型: {}", query.log_type)),
        };

        let total_pages = ((logs.1 as f64) / (query.page_size as f64)).ceil() as u32;

        Ok(AiAnalysisLogResponse {
            logs: logs.0,
            total_count: logs.1,
            current_page: query.page,
            page_size: query.page_size,
            total_pages,
        })
    }

    /// 获取分类记录日志
    async fn get_classification_records(&self, query: &AiAnalysisLogQuery) -> Result<(Vec<AiAnalysisLogItem>, u64)> {
        let status_filter = query.status_filter.as_ref().and_then(|s| {
            match s.as_str() {
                "Classified" => Some(ClassificationStatus::Classified),
                "Failed" => Some(ClassificationStatus::Failed),
                "NeedsReview" => Some(ClassificationStatus::NeedsReview),
                _ => None,
            }
        });

        let (records, total_count) = self.video_repo.get_by_project_id_with_pagination(
            &query.project_id,
            query.page,
            query.page_size,
            status_filter.as_ref(),
            query.search_keyword.as_deref(),
        ).await?;

        let logs = records.into_iter().map(|record| {
            let (status_display, details) = match record.status {
                ClassificationStatus::Classified => {
                    ("分类成功".to_string(), format!("分类结果: {} (置信度: {:.1}%, 质量: {:.1}/10)", 
                        record.category, record.confidence * 100.0, record.quality_score * 10.0))
                },
                ClassificationStatus::Failed => {
                    ("分类失败".to_string(), record.error_message.clone().unwrap_or_else(|| "未知错误".to_string()))
                },
                ClassificationStatus::NeedsReview => {
                    ("需要审核".to_string(), format!("低置信度或质量评分 (置信度: {:.1}%, 质量: {:.1}/10)", 
                        record.confidence * 100.0, record.quality_score * 10.0))
                },
            };

            AiAnalysisLogItem {
                id: record.id,
                log_type: "record".to_string(),
                title: format!("视频分类 - {}", record.category),
                status: serde_json::to_string(&record.status).unwrap_or_default(),
                status_display,
                details,
                error_message: record.error_message,
                confidence: Some(record.confidence),
                quality_score: Some(record.quality_score),
                category: Some(record.category),
                video_file_path: None,
                retry_count: None,
                created_at: record.created_at,
                updated_at: record.updated_at,
            }
        }).collect();

        Ok((logs, total_count))
    }

    /// 获取分类任务日志
    async fn get_classification_tasks(&self, query: &AiAnalysisLogQuery) -> Result<(Vec<AiAnalysisLogItem>, u64)> {
        let status_filter = query.status_filter.as_ref().and_then(|s| {
            match s.as_str() {
                "Pending" => Some(TaskStatus::Pending),
                "Uploading" => Some(TaskStatus::Uploading),
                "Analyzing" => Some(TaskStatus::Analyzing),
                "Completed" => Some(TaskStatus::Completed),
                "Failed" => Some(TaskStatus::Failed),
                "Cancelled" => Some(TaskStatus::Cancelled),
                _ => None,
            }
        });

        let (tasks, total_count) = self.video_repo.get_tasks_by_project_id_with_pagination(
            &query.project_id,
            query.page,
            query.page_size,
            status_filter.as_ref(),
            query.search_keyword.as_deref(),
        ).await?;

        let logs = tasks.into_iter().map(|task| {
            let (status_display, details) = match task.status {
                TaskStatus::Pending => ("等待处理".to_string(), "任务已创建，等待处理".to_string()),
                TaskStatus::Uploading => ("上传中".to_string(), "正在上传视频到Gemini".to_string()),
                TaskStatus::Analyzing => ("分析中".to_string(), "正在进行AI分析".to_string()),
                TaskStatus::Completed => ("已完成".to_string(), "任务处理完成".to_string()),
                TaskStatus::Failed => {
                    ("处理失败".to_string(), task.error_message.clone().unwrap_or_else(|| "未知错误".to_string()))
                },
                TaskStatus::Cancelled => ("已取消".to_string(), "任务已被取消".to_string()),
            };

            let file_name = std::path::Path::new(&task.video_file_path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(&task.video_file_path);

            AiAnalysisLogItem {
                id: task.id,
                log_type: "task".to_string(),
                title: format!("分类任务 - {}", file_name),
                status: serde_json::to_string(&task.status).unwrap_or_default(),
                status_display,
                details,
                error_message: task.error_message,
                confidence: None,
                quality_score: None,
                category: None,
                video_file_path: Some(task.video_file_path),
                retry_count: Some(task.retry_count),
                created_at: task.created_at,
                updated_at: task.updated_at,
            }
        }).collect();

        Ok((logs, total_count))
    }

    /// 获取AI分析统计信息
    pub async fn get_analysis_stats(&self, project_id: &str) -> Result<AiAnalysisLogStats> {
        // 获取分类统计
        let classification_stats = self.video_repo.get_classification_stats(Some(project_id)).await?;

        // 计算最近24小时活动（这里简化处理，实际应该查询数据库）
        let recent_24h_activity = 0; // TODO: 实现24小时内的活动统计

        Ok(AiAnalysisLogStats {
            total_records: classification_stats.total_classifications.max(0) as u64,
            successful_classifications: classification_stats.successful_classifications.max(0) as u64,
            failed_classifications: classification_stats.failed_classifications.max(0) as u64,
            needs_review: classification_stats.needs_review_classifications.max(0) as u64,
            total_tasks: classification_stats.total_tasks.max(0) as u64,
            completed_tasks: classification_stats.completed_tasks.max(0) as u64,
            failed_tasks: classification_stats.failed_tasks.max(0) as u64,
            processing_tasks: classification_stats.processing_tasks.max(0) as u64,
            average_confidence: classification_stats.average_confidence,
            average_quality_score: classification_stats.average_quality_score,
            recent_24h_activity,
        })
    }

    /// 导出分析日志
    pub async fn export_analysis_logs(&self, project_id: &str, format: &str) -> Result<String> {
        match format {
            "csv" => self.export_to_csv(project_id).await,
            "json" => self.export_to_json(project_id).await,
            _ => Err(anyhow::anyhow!("不支持的导出格式: {}", format)),
        }
    }

    /// 导出为CSV格式
    async fn export_to_csv(&self, project_id: &str) -> Result<String> {
        // TODO: 实现CSV导出
        Ok(format!("CSV导出功能待实现 - 项目ID: {}", project_id))
    }

    /// 导出为JSON格式
    async fn export_to_json(&self, project_id: &str) -> Result<String> {
        // TODO: 实现JSON导出
        Ok(format!("JSON导出功能待实现 - 项目ID: {}", project_id))
    }
}
