use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, Semaphore};
use tracing::{debug, info};
use anyhow::Result;
use rusqlite::Connection;

/// 连接池配置
#[derive(Debug, Clone)]
pub struct ConnectionPoolConfig {
    /// 最小连接数
    pub min_connections: u32,
    /// 最大连接数
    pub max_connections: u32,
    /// 连接超时时间（秒）
    pub connection_timeout_seconds: u64,
    /// 空闲连接超时时间（秒）
    pub idle_timeout_seconds: u64,
    /// 连接验证间隔（秒）
    pub validation_interval_seconds: u64,
    /// 最大等待时间（秒）
    pub max_wait_seconds: u64,
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            min_connections: 2,
            max_connections: 10,
            connection_timeout_seconds: 30,
            idle_timeout_seconds: 300, // 5分钟
            validation_interval_seconds: 60, // 1分钟
            max_wait_seconds: 10,
        }
    }
}

/// 连接池统计信息
#[derive(Debug, Clone)]
pub struct ConnectionPoolStats {
    /// 当前活跃连接数
    pub active_connections: u32,
    /// 当前空闲连接数
    pub idle_connections: u32,
    /// 总连接数
    pub total_connections: u32,
    /// 等待连接的请求数
    pub waiting_requests: u32,
    /// 连接获取总次数
    pub total_acquisitions: u64,
    /// 连接获取成功次数
    pub successful_acquisitions: u64,
    /// 连接获取失败次数
    pub failed_acquisitions: u64,
    /// 平均等待时间（毫秒）
    pub average_wait_time_ms: f64,
    /// 连接池创建时间
    pub created_at: Instant,
    /// 最后统计更新时间
    pub last_updated: Instant,
}

impl Default for ConnectionPoolStats {
    fn default() -> Self {
        let now = Instant::now();
        Self {
            active_connections: 0,
            idle_connections: 0,
            total_connections: 0,
            waiting_requests: 0,
            total_acquisitions: 0,
            successful_acquisitions: 0,
            failed_acquisitions: 0,
            average_wait_time_ms: 0.0,
            created_at: now,
            last_updated: now,
        }
    }
}

/// 连接包装器
pub struct PooledConnection<T> {
    connection: Option<T>,
    created_at: Instant,
    last_used: Instant,
    usage_count: u64,
    is_valid: bool,
}

impl<T> PooledConnection<T> {
    fn new(connection: T) -> Self {
        let now = Instant::now();
        Self {
            connection: Some(connection),
            created_at: now,
            last_used: now,
            usage_count: 0,
            is_valid: true,
        }
    }

    fn take(&mut self) -> Option<T> {
        self.last_used = Instant::now();
        self.usage_count += 1;
        self.connection.take()
    }

    fn is_expired(&self, idle_timeout: Duration) -> bool {
        Instant::now().duration_since(self.last_used) > idle_timeout
    }

    fn mark_invalid(&mut self) {
        self.is_valid = false;
    }
}

/// 连接池管理器
pub struct ConnectionPoolManager<T> {
    config: ConnectionPoolConfig,
    connections: Arc<Mutex<Vec<PooledConnection<T>>>>,
    semaphore: Arc<Semaphore>,
    stats: Arc<Mutex<ConnectionPoolStats>>,
    connection_factory: Arc<dyn Fn() -> Result<T> + Send + Sync>,
}

impl<T: Send + 'static> ConnectionPoolManager<T> {
    /// 创建新的连接池管理器
    pub fn new<F>(config: ConnectionPoolConfig, connection_factory: F) -> Result<Self>
    where
        F: Fn() -> Result<T> + Send + Sync + 'static,
    {
        let semaphore = Arc::new(Semaphore::new(config.max_connections as usize));
        let connections = Arc::new(Mutex::new(Vec::new()));
        let stats = Arc::new(Mutex::new(ConnectionPoolStats {
            created_at: Instant::now(),
            last_updated: Instant::now(),
            ..Default::default()
        }));

        let manager = Self {
            config,
            connections,
            semaphore,
            stats,
            connection_factory: Arc::new(connection_factory),
        };

        // 预创建最小连接数
        manager.initialize_min_connections()?;

        // 启动维护任务
        manager.start_maintenance_task();

        info!("连接池管理器已创建，最小连接数: {}, 最大连接数: {}", 
              manager.config.min_connections, manager.config.max_connections);

        Ok(manager)
    }

    /// 获取连接
    pub async fn acquire(&self) -> Result<T> {
        let start_time = Instant::now();
        
        // 更新统计信息
        {
            let mut stats = self.stats.lock().await;
            stats.total_acquisitions += 1;
            stats.waiting_requests += 1;
        }

        // 等待信号量
        let permit = tokio::time::timeout(
            Duration::from_secs(self.config.max_wait_seconds),
            self.semaphore.acquire()
        ).await;

        let _permit = match permit {
            Ok(Ok(permit)) => permit,
            Ok(Err(_)) => {
                self.update_failed_acquisition(start_time).await;
                return Err(anyhow::anyhow!("连接池信号量获取失败"));
            }
            Err(_) => {
                self.update_failed_acquisition(start_time).await;
                return Err(anyhow::anyhow!("获取连接超时"));
            }
        };

        // 尝试从池中获取连接
        let connection: Option<Connection> = {
            let mut connections = self.connections.lock().await;
            
            // 查找可用连接
            for i in 0..connections.len() {
                if connections[i].is_valid && connections[i].connection.is_some() {
                    let mut pooled_conn = connections.remove(i);
                    if let Some(conn) = pooled_conn.take() {
                        self.update_successful_acquisition(start_time).await;
                        return Ok(conn);
                    }
                }
            }
            
            // 没有可用连接，创建新连接
            None
        };

        // 创建新连接
        match (self.connection_factory)() {
            Ok(new_connection) => {
                self.update_successful_acquisition(start_time).await;
                debug!("创建新数据库连接");
                Ok(new_connection)
            }
            Err(e) => {
                self.update_failed_acquisition(start_time).await;
                Err(e)
            }
        }
    }

    /// 释放连接回池中
    pub async fn release(&self, connection: T) {
        let mut connections = self.connections.lock().await;
        
        // 检查池是否已满
        if connections.len() < self.config.max_connections as usize {
            connections.push(PooledConnection::new(connection));
            debug!("连接已释放回池中");
        } else {
            debug!("连接池已满，丢弃连接");
        }

        // 更新统计信息
        let mut stats = self.stats.lock().await;
        stats.active_connections = stats.active_connections.saturating_sub(1);
        stats.idle_connections = connections.len() as u32;
        stats.total_connections = stats.active_connections + stats.idle_connections;
        stats.last_updated = Instant::now();
    }

    /// 获取连接池统计信息
    pub async fn get_stats(&self) -> ConnectionPoolStats {
        let stats = self.stats.lock().await;
        stats.clone()
    }

    /// 清理过期连接
    pub async fn cleanup_expired_connections(&self) -> usize {
        let mut connections = self.connections.lock().await;
        let idle_timeout = Duration::from_secs(self.config.idle_timeout_seconds);
        
        let initial_count = connections.len();
        connections.retain(|conn| !conn.is_expired(idle_timeout));
        let removed_count = initial_count - connections.len();

        if removed_count > 0 {
            debug!("清理过期连接: {} 个", removed_count);
        }

        // 更新统计信息
        let mut stats = self.stats.lock().await;
        stats.idle_connections = connections.len() as u32;
        stats.total_connections = stats.active_connections + stats.idle_connections;
        stats.last_updated = Instant::now();

        removed_count
    }

    /// 验证连接有效性
    pub async fn validate_connections(&self) -> usize {
        let mut connections = self.connections.lock().await;
        let mut invalid_count = 0;

        for conn in connections.iter_mut() {
            // 这里应该实现具体的连接验证逻辑
            // 简化实现：假设所有连接都有效
            if !conn.is_valid {
                invalid_count += 1;
            }
        }

        // 移除无效连接
        connections.retain(|conn| conn.is_valid);

        if invalid_count > 0 {
            debug!("移除无效连接: {} 个", invalid_count);
        }

        invalid_count
    }

    /// 初始化最小连接数
    fn initialize_min_connections(&self) -> Result<()> {
        let min_connections = self.config.min_connections as usize;
        
        for _ in 0..min_connections {
            let connection = (self.connection_factory)()?;
            // 这里需要异步处理，但为了简化，我们先跳过
            // 在实际实现中，应该使用异步方法
        }

        info!("初始化最小连接数: {}", min_connections);
        Ok(())
    }

    /// 启动维护任务
    fn start_maintenance_task(&self) {
        let connections = self.connections.clone();
        let stats = self.stats.clone();
        let config = self.config.clone();

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(config.validation_interval_seconds));
            
            loop {
                interval.tick().await;
                
                // 清理过期连接
                {
                    let mut conns = connections.lock().await;
                    let idle_timeout = Duration::from_secs(config.idle_timeout_seconds);
                    let initial_count = conns.len();
                    conns.retain(|conn| !conn.is_expired(idle_timeout));
                    let removed_count = initial_count - conns.len();
                    
                    if removed_count > 0 {
                        debug!("维护任务清理过期连接: {} 个", removed_count);
                    }
                }

                // 更新统计信息
                {
                    let mut stats_guard = stats.lock().await;
                    let conns = connections.lock().await;
                    stats_guard.idle_connections = conns.len() as u32;
                    stats_guard.total_connections = stats_guard.active_connections + stats_guard.idle_connections;
                    stats_guard.last_updated = Instant::now();
                }
            }
        });
    }

    /// 更新成功获取连接的统计信息
    async fn update_successful_acquisition(&self, start_time: Instant) {
        let mut stats = self.stats.lock().await;
        stats.successful_acquisitions += 1;
        stats.waiting_requests = stats.waiting_requests.saturating_sub(1);
        stats.active_connections += 1;
        
        let wait_time = start_time.elapsed().as_millis() as f64;
        stats.average_wait_time_ms = (stats.average_wait_time_ms * (stats.successful_acquisitions - 1) as f64 + wait_time) / stats.successful_acquisitions as f64;
        stats.last_updated = Instant::now();
    }

    /// 更新失败获取连接的统计信息
    async fn update_failed_acquisition(&self, _start_time: Instant) {
        let mut stats = self.stats.lock().await;
        stats.failed_acquisitions += 1;
        stats.waiting_requests = stats.waiting_requests.saturating_sub(1);
        stats.last_updated = Instant::now();
    }
}

/// 连接池健康检查
pub struct ConnectionPoolHealthChecker;

impl ConnectionPoolHealthChecker {
    /// 检查连接池健康状态
    pub fn check_health<T>(stats: &ConnectionPoolStats, config: &ConnectionPoolConfig) -> PoolHealthStatus {
        let mut issues = Vec::new();
        let mut overall_status = HealthStatus::Healthy;

        // 检查连接利用率
        let utilization = stats.active_connections as f64 / config.max_connections as f64;
        if utilization > 0.9 {
            issues.push("连接池利用率过高 (>90%)".to_string());
            overall_status = HealthStatus::Warning;
        }

        // 检查失败率
        if stats.total_acquisitions > 0 {
            let failure_rate = stats.failed_acquisitions as f64 / stats.total_acquisitions as f64;
            if failure_rate > 0.1 {
                issues.push("连接获取失败率过高 (>10%)".to_string());
                overall_status = HealthStatus::Critical;
            }
        }

        // 检查等待时间
        if stats.average_wait_time_ms > 1000.0 {
            issues.push("平均等待时间过长 (>1秒)".to_string());
            if overall_status == HealthStatus::Healthy {
                overall_status = HealthStatus::Warning;
            }
        }

        // 检查等待请求数
        if stats.waiting_requests > config.max_connections / 2 {
            issues.push("等待连接的请求过多".to_string());
            overall_status = HealthStatus::Critical;
        }

        let recommendations = Self::generate_recommendations(&issues);
        PoolHealthStatus {
            status: overall_status,
            issues,
            recommendations,
        }
    }

    /// 生成优化建议
    fn generate_recommendations(issues: &[String]) -> Vec<String> {
        let mut recommendations = Vec::new();

        for issue in issues {
            if issue.contains("利用率过高") {
                recommendations.push("考虑增加最大连接数".to_string());
            }
            if issue.contains("失败率过高") {
                recommendations.push("检查数据库服务器状态和网络连接".to_string());
            }
            if issue.contains("等待时间过长") {
                recommendations.push("优化查询性能或增加连接数".to_string());
            }
            if issue.contains("等待请求过多") {
                recommendations.push("增加连接池大小或优化应用程序并发控制".to_string());
            }
        }

        recommendations
    }
}

/// 健康状态
#[derive(Debug, Clone, PartialEq)]
pub enum HealthStatus {
    Healthy,
    Warning,
    Critical,
}

/// 连接池健康状态
#[derive(Debug, Clone)]
pub struct PoolHealthStatus {
    pub status: HealthStatus,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}
