use anyhow::Result;
use chrono::{DateTime, Utc, Duration};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::time::{interval, Duration as TokioDuration};
use tracing::{debug, info, warn, error};

use crate::data::repositories::workflow_execution_record_repository::{
    WorkflowExecutionRecordRepository, ExecutionStatistics
};
use crate::data::repositories::workflow_execution_environment_repository::WorkflowExecutionEnvironmentRepository;
use crate::data::models::workflow_execution_environment::HealthStatus;

/// 系统监控服务
/// 负责监控工作流系统的性能、健康状态和执行队列
#[derive(Clone)]
pub struct WorkflowMonitoringService {
    execution_record_repository: WorkflowExecutionRecordRepository,
    execution_environment_repository: WorkflowExecutionEnvironmentRepository,
    monitoring_config: MonitoringConfig,
}

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// 健康检查间隔（秒）
    pub health_check_interval_seconds: u64,
    /// 性能统计间隔（秒）
    pub performance_stats_interval_seconds: u64,
    /// 队列监控间隔（秒）
    pub queue_monitoring_interval_seconds: u64,
    /// 告警阈值配置
    pub alert_thresholds: AlertThresholds,
}

/// 告警阈值配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    /// 最大失败率（0.0-1.0）
    pub max_failure_rate: f64,
    /// 最大平均响应时间（毫秒）
    pub max_avg_response_time_ms: i32,
    /// 最大队列长度
    pub max_queue_length: u32,
    /// 最小可用环境数量
    pub min_available_environments: u32,
}

/// 系统健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemHealthStatus {
    pub overall_status: OverallHealthStatus,
    pub environment_health: Vec<EnvironmentHealth>,
    pub execution_stats: ExecutionStatistics,
    pub queue_status: QueueStatus,
    pub alerts: Vec<Alert>,
    pub last_updated: DateTime<Utc>,
}

/// 整体健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OverallHealthStatus {
    Healthy,
    Warning,
    Critical,
    Unknown,
}

/// 环境健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentHealth {
    pub environment_id: i64,
    pub environment_name: String,
    pub health_status: HealthStatus,
    pub last_health_check: Option<DateTime<Utc>>,
    pub response_time_ms: Option<i32>,
    pub success_rate: f64,
    pub current_load: u32,
    pub max_capacity: u32,
}

/// 队列状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStatus {
    pub pending_executions: u32,
    pub running_executions: u32,
    pub average_wait_time_seconds: Option<f64>,
    pub oldest_pending_execution: Option<DateTime<Utc>>,
}

/// 告警信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
    pub id: String,
    pub alert_type: AlertType,
    pub severity: AlertSeverity,
    pub message: String,
    pub details: Option<serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub resolved_at: Option<DateTime<Utc>>,
}

/// 告警类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertType {
    EnvironmentDown,
    HighFailureRate,
    SlowResponse,
    QueueBacklog,
    StorageSpaceLow,
    SystemError,
}

/// 告警严重程度
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AlertSeverity {
    Info,
    Warning,
    Critical,
}

/// 性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    pub timestamp: DateTime<Utc>,
    pub total_executions_last_hour: u32,
    pub average_execution_time_seconds: Option<f64>,
    pub success_rate_last_hour: f64,
    pub environment_utilization: HashMap<i64, f64>,
    pub queue_length_over_time: Vec<(DateTime<Utc>, u32)>,
    pub response_times: HashMap<i64, Vec<i32>>,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            health_check_interval_seconds: 300, // 5分钟
            performance_stats_interval_seconds: 60, // 1分钟
            queue_monitoring_interval_seconds: 30, // 30秒
            alert_thresholds: AlertThresholds {
                max_failure_rate: 0.1, // 10%
                max_avg_response_time_ms: 30000, // 30秒
                max_queue_length: 100,
                min_available_environments: 1,
            },
        }
    }
}

impl WorkflowMonitoringService {
    /// 创建新的监控服务
    pub fn new(
        execution_record_repository: WorkflowExecutionRecordRepository,
        execution_environment_repository: WorkflowExecutionEnvironmentRepository,
        config: Option<MonitoringConfig>,
    ) -> Self {
        Self {
            execution_record_repository,
            execution_environment_repository,
            monitoring_config: config.unwrap_or_default(),
        }
    }

    /// 启动监控服务
    pub async fn start_monitoring(&self) -> Result<()> {
        info!("启动工作流监控服务");

        // 启动健康检查任务
        let health_check_service = self.clone();
        tokio::spawn(async move {
            health_check_service.run_health_check_loop().await;
        });

        // 启动性能统计任务
        let performance_service = self.clone();
        tokio::spawn(async move {
            performance_service.run_performance_monitoring_loop().await;
        });

        // 启动队列监控任务
        let queue_service = self.clone();
        tokio::spawn(async move {
            queue_service.run_queue_monitoring_loop().await;
        });

        Ok(())
    }

    /// 获取系统健康状态
    pub async fn get_system_health(&self) -> Result<SystemHealthStatus> {
        // 获取环境健康状态
        let environment_health = self.get_environment_health().await?;
        
        // 获取执行统计
        let execution_stats = self.execution_record_repository
            .get_execution_statistics(None)?;
        
        // 获取队列状态
        let queue_status = self.get_queue_status().await?;
        
        // 生成告警
        let alerts = self.generate_alerts(&environment_health, &execution_stats, &queue_status).await?;
        
        // 计算整体健康状态
        let overall_status = self.calculate_overall_health(&environment_health, &execution_stats, &alerts);

        Ok(SystemHealthStatus {
            overall_status,
            environment_health,
            execution_stats,
            queue_status,
            alerts,
            last_updated: Utc::now(),
        })
    }

    /// 获取性能指标
    pub async fn get_performance_metrics(&self) -> Result<PerformanceMetrics> {
        let now = Utc::now();
        let one_hour_ago = now - Duration::hours(1);

        // 获取最近一小时的执行统计
        let filter = crate::data::models::workflow_execution_record::ExecutionRecordFilter {
            date_from: Some(one_hour_ago),
            date_to: Some(now),
            ..Default::default()
        };

        let recent_stats = self.execution_record_repository
            .get_execution_statistics(Some(&filter))?;

        // 获取环境利用率
        let environment_utilization = self.calculate_environment_utilization().await?;

        // 获取队列长度历史（简化实现）
        let queue_length_over_time = vec![(now, self.get_current_queue_length().await?)];

        // 获取响应时间数据
        let response_times = self.get_response_times().await?;

        Ok(PerformanceMetrics {
            timestamp: now,
            total_executions_last_hour: recent_stats.total_executions,
            average_execution_time_seconds: recent_stats.average_duration_seconds,
            success_rate_last_hour: recent_stats.success_rate,
            environment_utilization,
            queue_length_over_time,
            response_times,
        })
    }

    /// 健康检查循环
    async fn run_health_check_loop(&self) {
        let mut interval = interval(TokioDuration::from_secs(
            self.monitoring_config.health_check_interval_seconds
        ));

        loop {
            interval.tick().await;
            
            if let Err(e) = self.perform_health_checks().await {
                error!("健康检查失败: {}", e);
            }
        }
    }

    /// 性能监控循环
    async fn run_performance_monitoring_loop(&self) {
        let mut interval = interval(TokioDuration::from_secs(
            self.monitoring_config.performance_stats_interval_seconds
        ));

        loop {
            interval.tick().await;
            
            if let Err(e) = self.collect_performance_metrics().await {
                error!("性能指标收集失败: {}", e);
            }
        }
    }

    /// 队列监控循环
    async fn run_queue_monitoring_loop(&self) {
        let mut interval = interval(TokioDuration::from_secs(
            self.monitoring_config.queue_monitoring_interval_seconds
        ));

        loop {
            interval.tick().await;
            
            if let Err(e) = self.monitor_execution_queue().await {
                error!("队列监控失败: {}", e);
            }
        }
    }

    /// 执行健康检查
    async fn perform_health_checks(&self) -> Result<()> {
        debug!("执行环境健康检查");
        
        let health_results = self.execution_environment_repository
            .health_check_all().await?;

        for (env_id, health_status) in health_results {
            debug!("环境 {} 健康状态: {:?}", env_id, health_status);
        }

        Ok(())
    }

    /// 收集性能指标
    async fn collect_performance_metrics(&self) -> Result<()> {
        debug!("收集性能指标");
        
        let metrics = self.get_performance_metrics().await?;
        
        // 这里可以将指标存储到时序数据库或日志中
        debug!("性能指标: 成功率={:.2}%, 平均执行时间={:?}秒", 
               metrics.success_rate_last_hour * 100.0,
               metrics.average_execution_time_seconds);

        Ok(())
    }

    /// 监控执行队列
    async fn monitor_execution_queue(&self) -> Result<()> {
        debug!("监控执行队列");
        
        let queue_status = self.get_queue_status().await?;
        
        if queue_status.pending_executions > self.monitoring_config.alert_thresholds.max_queue_length {
            warn!("队列积压: {} 个待执行任务", queue_status.pending_executions);
        }

        Ok(())
    }

    /// 获取环境健康状态
    async fn get_environment_health(&self) -> Result<Vec<EnvironmentHealth>> {
        let environments = self.execution_environment_repository.find_all(None)?;
        let mut health_list = Vec::new();

        for env in environments {
            if let Some(env_id) = env.id {
                let health = EnvironmentHealth {
                    environment_id: env_id,
                    environment_name: env.name,
                    health_status: env.health_status,
                    last_health_check: env.last_health_check,
                    response_time_ms: env.average_response_time_ms,
                    success_rate: env.success_rate,
                    current_load: self.calculate_current_load(env_id).await?,
                    max_capacity: env.max_concurrent_jobs as u32,
                };
                health_list.push(health);
            }
        }

        Ok(health_list)
    }

    /// 获取队列状态
    async fn get_queue_status(&self) -> Result<QueueStatus> {
        use crate::data::models::workflow_execution_record::{ExecutionStatus, ExecutionRecordFilter};

        // 获取待执行任务数量
        let pending_filter = ExecutionRecordFilter {
            status: Some(ExecutionStatus::Pending),
            ..Default::default()
        };
        let pending_records = self.execution_record_repository.find_all(Some(&pending_filter))?;
        let pending_count = pending_records.len() as u32;

        // 获取正在执行任务数量
        let running_filter = ExecutionRecordFilter {
            status: Some(ExecutionStatus::Running),
            ..Default::default()
        };
        let running_records = self.execution_record_repository.find_all(Some(&running_filter))?;
        let running_count = running_records.len() as u32;

        // 计算平均等待时间
        let average_wait_time = if !pending_records.is_empty() {
            let now = Utc::now();
            let total_wait_time: i64 = pending_records.iter()
                .map(|record| (now - record.created_at).num_seconds())
                .sum();
            Some(total_wait_time as f64 / pending_records.len() as f64)
        } else {
            None
        };

        // 获取最旧的待执行任务
        let oldest_pending = pending_records.iter()
            .min_by_key(|record| record.created_at)
            .map(|record| record.created_at);

        Ok(QueueStatus {
            pending_executions: pending_count,
            running_executions: running_count,
            average_wait_time_seconds: average_wait_time,
            oldest_pending_execution: oldest_pending,
        })
    }

    /// 计算环境当前负载
    async fn calculate_current_load(&self, environment_id: i64) -> Result<u32> {
        use crate::data::models::workflow_execution_record::{ExecutionStatus, ExecutionRecordFilter};

        let filter = ExecutionRecordFilter {
            status: Some(ExecutionStatus::Running),
            ..Default::default()
        };

        let running_records = self.execution_record_repository.find_all(Some(&filter))?;

        // 计算在该环境上运行的任务数量
        let load = running_records.iter()
            .filter(|record| record.execution_environment_id == Some(environment_id))
            .count() as u32;

        Ok(load)
    }

    /// 计算整体健康状态
    fn calculate_overall_health(
        &self,
        environment_health: &[EnvironmentHealth],
        _execution_stats: &ExecutionStatistics,
        alerts: &[Alert],
    ) -> OverallHealthStatus {
        // 检查是否有严重告警
        if alerts.iter().any(|alert| matches!(alert.severity, AlertSeverity::Critical)) {
            return OverallHealthStatus::Critical;
        }

        // 检查是否有警告告警
        if alerts.iter().any(|alert| matches!(alert.severity, AlertSeverity::Warning)) {
            return OverallHealthStatus::Warning;
        }

        // 检查环境健康状态
        let healthy_envs = environment_health.iter()
            .filter(|env| matches!(env.health_status, HealthStatus::Healthy))
            .count();

        if healthy_envs == 0 {
            return OverallHealthStatus::Critical;
        }

        if healthy_envs < environment_health.len() {
            return OverallHealthStatus::Warning;
        }

        OverallHealthStatus::Healthy
    }

    /// 生成告警（简化版本）
    async fn generate_alerts(
        &self,
        environment_health: &[EnvironmentHealth],
        execution_stats: &ExecutionStatistics,
        queue_status: &QueueStatus,
    ) -> Result<Vec<Alert>> {
        let mut alerts = Vec::new();
        let now = Utc::now();

        // 检查环境健康状态
        let healthy_envs = environment_health.iter()
            .filter(|env| matches!(env.health_status, HealthStatus::Healthy))
            .count() as u32;

        if healthy_envs < self.monitoring_config.alert_thresholds.min_available_environments {
            alerts.push(Alert {
                id: format!("env_availability_{}", now.timestamp()),
                alert_type: AlertType::EnvironmentDown,
                severity: AlertSeverity::Critical,
                message: format!("可用环境数量不足: {} < {}",
                               healthy_envs,
                               self.monitoring_config.alert_thresholds.min_available_environments),
                details: Some(serde_json::json!({
                    "healthy_environments": healthy_envs,
                    "required_minimum": self.monitoring_config.alert_thresholds.min_available_environments
                })),
                created_at: now,
                resolved_at: None,
            });
        }

        // 检查队列积压
        if queue_status.pending_executions > self.monitoring_config.alert_thresholds.max_queue_length {
            alerts.push(Alert {
                id: format!("queue_backlog_{}", now.timestamp()),
                alert_type: AlertType::QueueBacklog,
                severity: AlertSeverity::Warning,
                message: format!("队列积压严重: {} > {}",
                               queue_status.pending_executions,
                               self.monitoring_config.alert_thresholds.max_queue_length),
                details: Some(serde_json::json!({
                    "pending_executions": queue_status.pending_executions,
                    "threshold": self.monitoring_config.alert_thresholds.max_queue_length
                })),
                created_at: now,
                resolved_at: None,
            });
        }

        Ok(alerts)
    }



    /// 计算环境利用率
    async fn calculate_environment_utilization(&self) -> Result<HashMap<i64, f64>> {
        let environments = self.execution_environment_repository.find_all(None)?;
        let mut utilization = HashMap::new();

        for env in environments {
            if let Some(env_id) = env.id {
                // 简化实现 - 在实际应用中应该计算实际利用率
                let util = if env.is_available { 0.5 } else { 0.0 };
                utilization.insert(env_id, util);
            }
        }

        Ok(utilization)
    }

    /// 获取当前队列长度
    async fn get_current_queue_length(&self) -> Result<u32> {
        // 简化实现
        Ok(0)
    }

    /// 获取响应时间数据
    async fn get_response_times(&self) -> Result<HashMap<i64, Vec<i32>>> {
        // 简化实现
        let mut response_times = HashMap::new();
        response_times.insert(1, vec![1000, 1200, 800]);
        Ok(response_times)
    }


}
