use std::sync::Arc;
use std::path::Path;
use anyhow::Result;
use tokio::time::Instant;
use tracing::{info, error};

use crate::data::models::template::{Template, ImportTemplateRequest};
use crate::business::services::template_import_service::{TemplateImportService, ImportEventCallback};
use crate::business::services::template_service::TemplateService;
use crate::business::services::chunked_upload_service::{ChunkedUploadService, ChunkedUploadConfig};
use crate::business::services::template_cache_service::TemplateCacheService;
use crate::business::services::performance_monitor::PerformanceMonitor;
use crate::business::services::cloud_upload_service::CloudUploadService;
use crate::infrastructure::database::Database;

/// 增强的模板导入服务
/// 集成了性能优化、缓存和监控功能
pub struct EnhancedTemplateImportService {
    base_service: TemplateImportService,
    template_service: TemplateService,
    chunked_upload: Arc<ChunkedUploadService>,
    cache_service: Arc<TemplateCacheService>,
    performance_monitor: Arc<PerformanceMonitor>,
    database: Arc<Database>,
}

impl EnhancedTemplateImportService {
    pub fn new(database: Arc<Database>) -> Self {
        let cloud_service = Arc::new(CloudUploadService::new());
        let chunked_upload_config = ChunkedUploadConfig {
            chunk_size: 10 * 1024 * 1024, // 10MB chunks for better performance
            max_concurrent: 5, // Higher concurrency
            max_retries: 5,
            retry_delay_ms: 500,
        };

        Self {
            base_service: TemplateImportService::new(database.clone()),
            template_service: TemplateService::new(database.clone()),
            chunked_upload: Arc::new(ChunkedUploadService::with_config(
                cloud_service,
                chunked_upload_config,
            )),
            cache_service: Arc::new(TemplateCacheService::new()),
            performance_monitor: Arc::new(PerformanceMonitor::new()),
            database,
        }
    }

    /// 高性能模板导入
    pub async fn import_template_optimized(
        &self,
        request: ImportTemplateRequest,
        callback: Option<ImportEventCallback>,
    ) -> Result<String> {
        let timer = self.performance_monitor.start_timer("template_import_duration")
            .add_tag("auto_upload".to_string(), request.auto_upload.to_string());

        let start_time = Instant::now();
        
        // 记录导入开始
        self.performance_monitor.increment_counter("template_import_started", 1.0);

        let result = self.import_with_optimizations(request, callback).await;

        // 记录性能指标
        let duration = start_time.elapsed();
        timer.finish(&self.performance_monitor);

        match &result {
            Ok(template_id) => {
                self.performance_monitor.increment_counter("template_import_success", 1.0);
                
                // 预热缓存
                if let Ok(Some(template)) = self.template_service.get_template_by_id(template_id).await {
                    self.cache_service.put(template_id.clone(), template).await;
                }
                
                println!("✅ 模板导入成功，耗时: {:?}", duration);
            }
            Err(e) => {
                self.performance_monitor.increment_counter("template_import_failed", 1.0);
                println!("❌ 模板导入失败，耗时: {:?}，错误: {}", duration, e);
            }
        }

        result
    }

    /// 批量导入优化
    pub async fn batch_import_optimized(
        &self,
        requests: Vec<ImportTemplateRequest>,
        max_concurrent: Option<usize>,
    ) -> Result<Vec<Result<String>>> {
        let batch_size = requests.len();
        let concurrent_limit = max_concurrent.unwrap_or(3);

        info!(
            batch_size = %batch_size,
            concurrent_limit = %concurrent_limit,
            "开始批量导入模板"
        );
        let timer = self.performance_monitor.start_timer("batch_import_duration")
            .add_tag("batch_size".to_string(), requests.len().to_string());

        let concurrent_limit = max_concurrent.unwrap_or(3);
        let semaphore = Arc::new(tokio::sync::Semaphore::new(concurrent_limit));
        let mut handles = Vec::new();

        // 并发处理导入请求
        for request in requests {
            let semaphore = semaphore.clone();
            let service = self.clone();
            
            let handle = tokio::spawn(async move {
                let _permit = semaphore.acquire().await.unwrap();
                service.import_template_optimized(request, None).await
            });
            
            handles.push(handle);
        }

        // 等待所有任务完成
        let mut results = Vec::new();
        for handle in handles {
            results.push(handle.await?);
        }

        timer.finish(&self.performance_monitor);

        // 统计结果
        let success_count = results.iter().filter(|r| r.is_ok()).count();
        let failure_count = results.iter().filter(|r| r.is_err()).count();

        info!(
            batch_size = %batch_size,
            success_count = %success_count,
            failure_count = %failure_count,
            "批量导入完成"
        );

        // 记录失败的详细信息
        for (index, result) in results.iter().enumerate() {
            if let Err(e) = result {
                error!(
                    index = %index,
                    error = %e,
                    "批量导入中的单个模板失败"
                );
            }
        }

        Ok(results)
    }

    /// 获取缓存的模板
    pub async fn get_template_cached(&self, template_id: &str) -> Result<Option<Template>> {
        // 先尝试从缓存获取
        if let Some(template) = self.cache_service.get(template_id).await {
            self.performance_monitor.increment_counter("template_cache_hit", 1.0);
            return Ok(Some(template));
        }

        // 缓存未命中，从数据库获取
        self.performance_monitor.increment_counter("template_cache_miss", 1.0);
        let timer = self.performance_monitor.start_timer("database_query_duration");

        let template = self.template_service.get_template_by_id(template_id).await?;
        timer.finish(&self.performance_monitor);

        // 更新缓存
        if let Some(ref t) = template {
            self.cache_service.put(template_id.to_string(), t.clone()).await;
        }

        Ok(template)
    }

    /// 预热缓存
    pub async fn warm_cache(&self, template_ids: Vec<String>) -> Result<()> {
        let timer = self.performance_monitor.start_timer("cache_warmup_duration");
        
        let mut templates = Vec::new();
        for id in template_ids {
            if let Ok(Some(template)) = self.template_service.get_template_by_id(&id).await {
                templates.push(template);
            }
        }

        self.cache_service.warm_up(templates).await;
        timer.finish(&self.performance_monitor);
        
        Ok(())
    }

    /// 获取性能报告
    pub async fn get_performance_report(&self) -> serde_json::Value {
        let overview = self.performance_monitor.get_performance_overview().await;
        serde_json::to_value(overview).unwrap_or_default()
    }

    /// 获取缓存统计
    pub async fn get_cache_stats(&self) -> serde_json::Value {
        serde_json::to_value(self.cache_service.get_stats().await).unwrap()
    }

    /// 清理性能数据
    pub async fn cleanup_performance_data(&self, older_than_hours: u64) {
        let duration = std::time::Duration::from_secs(older_than_hours * 3600);
        self.performance_monitor.cleanup_old_metrics(duration).await;
    }

    /// 内部优化导入实现
    async fn import_with_optimizations(
        &self,
        request: ImportTemplateRequest,
        callback: Option<ImportEventCallback>,
    ) -> Result<String> {
        // 检查文件大小，决定使用普通上传还是分片上传
        let file_path = Path::new(&request.file_path);
        let file_size = file_path.metadata()?.len();
        
        // 大于50MB的文件使用分片上传
        const CHUNKED_UPLOAD_THRESHOLD: u64 = 50 * 1024 * 1024;
        
        if request.auto_upload && file_size > CHUNKED_UPLOAD_THRESHOLD {
            self.import_with_chunked_upload(request, callback).await
        } else {
            // 使用基础服务进行导入
            self.base_service.import_template(request, callback).await
        }
    }

    /// 使用分片上传的导入流程
    async fn import_with_chunked_upload(
        &self,
        request: ImportTemplateRequest,
        callback: Option<ImportEventCallback>,
    ) -> Result<String> {
        // 这里需要修改基础导入服务以支持分片上传
        // 暂时使用基础服务，后续可以扩展
        self.base_service.import_template(request, callback).await
    }

    /// 智能重试机制
    async fn retry_with_backoff<F, T>(&self, operation: F, max_retries: usize) -> Result<T>
    where
        F: Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T>> + Send>>,
    {
        let mut last_error = None;
        
        for attempt in 0..max_retries {
            match operation().await {
                Ok(result) => return Ok(result),
                Err(e) => {
                    last_error = Some(e);
                    if attempt < max_retries - 1 {
                        let delay = std::time::Duration::from_millis(
                            1000 * (2_u64.pow(attempt as u32))
                        );
                        tokio::time::sleep(delay).await;
                    }
                }
            }
        }
        
        Err(last_error.unwrap())
    }

    /// 内存使用监控
    pub async fn monitor_memory_usage(&self) {
        let memory_info = self.get_memory_info().await;
        self.performance_monitor.record_memory_usage(
            "template_service_memory",
            memory_info.used_bytes,
        );
    }

    /// 获取内存使用信息
    async fn get_memory_info(&self) -> MemoryInfo {
        // 简单的内存使用估算
        let cache_memory = self.cache_service.get_stats().await.memory_usage_bytes;
        
        MemoryInfo {
            used_bytes: cache_memory as u64,
            available_bytes: 0, // 需要系统API获取
        }
    }
}

impl Clone for EnhancedTemplateImportService {
    fn clone(&self) -> Self {
        Self {
            base_service: TemplateImportService::new(self.database.clone()),
            template_service: TemplateService::new(self.database.clone()),
            chunked_upload: self.chunked_upload.clone(),
            cache_service: self.cache_service.clone(),
            performance_monitor: self.performance_monitor.clone(),
            database: self.database.clone(),
        }
    }
}

/// 内存使用信息
#[derive(Debug)]
struct MemoryInfo {
    used_bytes: u64,
    available_bytes: u64,
}

/// 性能优化配置
#[derive(Debug, Clone)]
pub struct PerformanceConfig {
    /// 启用缓存
    pub enable_cache: bool,
    /// 启用性能监控
    pub enable_monitoring: bool,
    /// 启用分片上传
    pub enable_chunked_upload: bool,
    /// 分片上传阈值（字节）
    pub chunked_upload_threshold: u64,
    /// 最大并发数
    pub max_concurrent_uploads: usize,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            enable_cache: true,
            enable_monitoring: true,
            enable_chunked_upload: true,
            chunked_upload_threshold: 50 * 1024 * 1024, // 50MB
            max_concurrent_uploads: 5,
        }
    }
}
