use anyhow::{anyhow, Result};
use crate::data::models::video_generation::{
    VideoGenerationTask, VideoGenerationStatus, VideoGenerationQueryParams,
    CreateVideoGenerationRequest
};
use crate::data::repositories::video_generation_repository::VideoGenerationRepository;
use crate::data::repositories::model_repository::ModelRepository;
use crate::infrastructure::video_generation_service::VideoGenerationService as ApiService;
use crate::business::services::cloud_upload_service::CloudUploadService;

/// 视频生成业务服务
/// 遵循 Tauri 开发规范的业务逻辑层设计
pub struct VideoGenerationService;

impl VideoGenerationService {
    /// 创建视频生成任务
    pub async fn create_task(
        repository: &VideoGenerationRepository,
        model_repository: &ModelRepository,
        request: CreateVideoGenerationRequest,
    ) -> Result<VideoGenerationTask> {
        // 验证模特是否存在
        let model = model_repository.get_by_id(&request.model_id)?
            .ok_or_else(|| anyhow!("模特不存在: {}", request.model_id))?;

        // 验证选中的照片是否存在
        if request.selected_photos.is_empty() {
            return Err(anyhow!("必须选择至少一张照片"));
        }

        // 验证照片是否属于该模特
        for photo_id in &request.selected_photos {
            let photo_exists = model.photos.iter().any(|p| &p.id == photo_id);
            if !photo_exists {
                return Err(anyhow!("照片不存在或不属于该模特: {}", photo_id));
            }
        }

        // 创建任务
        let task = VideoGenerationTask::new(
            request.model_id,
            request.prompt_config,
            request.selected_photos,
        );

        // 验证任务数据
        task.validate().map_err(|e| anyhow!(e))?;

        // 保存到数据库
        repository.create(&task)?;

        println!("✅ 视频生成任务创建成功: {}", task.id);

        Ok(task)
    }

    /// 执行视频生成任务
    pub async fn execute_task(
        repository: &VideoGenerationRepository,
        model_repository: &ModelRepository,
        task_id: &str,
    ) -> Result<VideoGenerationTask> {
        // 获取任务
        let mut task = repository.get_by_id(task_id)?
            .ok_or_else(|| anyhow!("任务不存在: {}", task_id))?;

        // 检查任务状态
        if !matches!(task.status, VideoGenerationStatus::Pending) {
            return Err(anyhow!("任务状态不允许执行: {:?}", task.status));
        }

        // 更新任务状态为处理中
        task.update_status(VideoGenerationStatus::Processing);
        repository.update(&task)?;

        println!("🚀 开始执行视频生成任务: {}", task_id);

        // 获取模特信息
        let model = model_repository.get_by_id(&task.model_id)?
            .ok_or_else(|| anyhow!("模特不存在: {}", task.model_id))?;

        // 获取第一张选中的照片作为生成图片
        let first_photo_id = &task.selected_photos[0];
        let photo = model.photos.iter()
            .find(|p| &p.id == first_photo_id)
            .ok_or_else(|| anyhow!("照片不存在: {}", first_photo_id))?;

        // 检查照片路径是否已经是云端URL
        let image_url = if photo.file_path.starts_with("https://") {
            // 如果已经是HTTPS URL，直接使用
            println!("📷 使用已有的云端图片URL: {}", photo.file_path);
            photo.file_path.clone()
        } else {
            // 如果是本地路径，上传到云存储
            println!("📤 本地图片需要上传到云存储: {}", photo.file_path);
            Self::upload_image_to_cloud(&photo.file_path).await?
        };

        // 执行视频生成
        let api_service = ApiService::new();
        match api_service.generate_video(
            task.prompt_config.product.clone(),
            task.prompt_config.scene.clone(),
            task.prompt_config.model_desc.clone(),
            image_url,
            task.prompt_config.template.clone(),
            task.prompt_config.duplicate,
        ).await {
            Ok(result) => {
                // 生成成功，更新任务结果
                task.set_result(result);
                repository.update(&task)?;
                println!("✅ 视频生成任务完成: {}", task_id);
            }
            Err(e) => {
                // 生成失败，更新错误信息
                let error_msg = format!("视频生成失败: {}", e);
                task.set_error(error_msg);
                repository.update(&task)?;
                println!("❌ 视频生成任务失败: {} - {}", task_id, e);
                return Err(e);
            }
        }

        Ok(task)
    }

    /// 获取视频生成任务
    pub fn get_task(
        repository: &VideoGenerationRepository,
        task_id: &str,
    ) -> Result<Option<VideoGenerationTask>> {
        repository.get_by_id(task_id)
    }

    /// 获取视频生成任务列表
    pub fn get_tasks(
        repository: &VideoGenerationRepository,
        params: &VideoGenerationQueryParams,
    ) -> Result<Vec<VideoGenerationTask>> {
        repository.search(params)
    }

    /// 取消视频生成任务
    pub fn cancel_task(
        repository: &VideoGenerationRepository,
        task_id: &str,
    ) -> Result<VideoGenerationTask> {
        let mut task = repository.get_by_id(task_id)?
            .ok_or_else(|| anyhow!("任务不存在: {}", task_id))?;

        // 只有等待中或处理中的任务可以取消
        if !matches!(task.status, VideoGenerationStatus::Pending | VideoGenerationStatus::Processing) {
            return Err(anyhow!("任务状态不允许取消: {:?}", task.status));
        }

        task.update_status(VideoGenerationStatus::Cancelled);
        repository.update(&task)?;

        println!("🚫 视频生成任务已取消: {}", task_id);

        Ok(task)
    }

    /// 删除视频生成任务
    pub fn delete_task(
        repository: &VideoGenerationRepository,
        task_id: &str,
    ) -> Result<()> {
        let task = repository.get_by_id(task_id)?
            .ok_or_else(|| anyhow!("任务不存在: {}", task_id))?;

        // 删除本地视频文件
        if let Some(result) = &task.result {
            for video_path in &result.video_paths {
                if std::path::Path::new(video_path).exists() {
                    if let Err(e) = std::fs::remove_file(video_path) {
                        println!("⚠️ 删除视频文件失败: {} - {}", video_path, e);
                    }
                }
            }
        }

        repository.delete(task_id)?;

        println!("🗑️ 视频生成任务已删除: {}", task_id);

        Ok(())
    }

    /// 重试视频生成任务
    pub async fn retry_task(
        repository: &VideoGenerationRepository,
        model_repository: &ModelRepository,
        task_id: &str,
    ) -> Result<VideoGenerationTask> {
        let mut task = repository.get_by_id(task_id)?
            .ok_or_else(|| anyhow!("任务不存在: {}", task_id))?;

        // 只有失败的任务可以重试
        if !matches!(task.status, VideoGenerationStatus::Failed) {
            return Err(anyhow!("只有失败的任务可以重试"));
        }

        // 重置任务状态
        task.update_status(VideoGenerationStatus::Pending);
        task.result = None;
        task.error_message = None;
        task.completed_at = None;
        repository.update(&task)?;

        println!("🔄 重试视频生成任务: {}", task_id);

        // 执行任务
        Self::execute_task(repository, model_repository, task_id).await
    }

    /// 获取模特的视频生成统计
    pub fn get_model_statistics(
        repository: &VideoGenerationRepository,
        model_id: &str,
    ) -> Result<VideoGenerationStatistics> {
        let params = VideoGenerationQueryParams {
            model_id: Some(model_id.to_string()),
            status: None,
            limit: None,
            offset: None,
        };

        let tasks = repository.search(&params)?;

        let total = tasks.len();
        let pending = tasks.iter().filter(|t| matches!(t.status, VideoGenerationStatus::Pending)).count();
        let processing = tasks.iter().filter(|t| matches!(t.status, VideoGenerationStatus::Processing)).count();
        let completed = tasks.iter().filter(|t| matches!(t.status, VideoGenerationStatus::Completed)).count();
        let failed = tasks.iter().filter(|t| matches!(t.status, VideoGenerationStatus::Failed)).count();
        let cancelled = tasks.iter().filter(|t| matches!(t.status, VideoGenerationStatus::Cancelled)).count();

        let total_videos = tasks.iter()
            .filter_map(|t| t.result.as_ref())
            .map(|r| r.video_urls.len())
            .sum();

        let avg_generation_time = if completed > 0 {
            let total_time: u64 = tasks.iter()
                .filter_map(|t| t.result.as_ref())
                .map(|r| r.generation_time)
                .sum();
            total_time / completed as u64
        } else {
            0
        };

        Ok(VideoGenerationStatistics {
            total,
            pending,
            processing,
            completed,
            failed,
            cancelled,
            total_videos,
            avg_generation_time,
        })
    }

    /// 上传图片到云存储并返回可访问的URL
    async fn upload_image_to_cloud(file_path: &str) -> Result<String> {
        println!("📤 正在上传图片到云存储: {}", file_path);

        // 创建云上传服务实例
        let upload_service = CloudUploadService::new();

        // 生成远程文件名
        let file_name = std::path::Path::new(file_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("image.jpg");

        let remote_key = format!("video-generation/images/{}", file_name);

        // 上传文件
        match upload_service.upload_file(file_path, Some(remote_key), None).await {
            Ok(upload_result) => {
                // 打印完整的上传结果
                println!("📋 完整上传结果: {:#?}", upload_result);

                if upload_result.success {
                    if let Some(remote_url) = upload_result.remote_url {
                        // 将S3 URL转换为可访问的CDN地址
                        let accessible_url = Self::convert_s3_to_cdn_url(&remote_url);
                        Ok(accessible_url)
                    } else if let Some(urn) = upload_result.urn {
                        // 将S3 URN转换为可访问的CDN地址
                        let accessible_url = Self::convert_s3_to_cdn_url(&urn);
                        Ok(accessible_url)
                    } else {
                        println!("⚠️ 上传成功但未返回URL或URN");
                        Err(anyhow!("上传成功但未返回URL"))
                    }
                } else {
                    let error_msg = upload_result.error_message
                        .unwrap_or_else(|| "未知上传错误".to_string());
                    println!("❌ 图片上传失败: {}", error_msg);
                    Err(anyhow!("图片上传失败: {}", error_msg))
                }
            }
            Err(e) => {
                println!("❌ 图片上传异常: {}", e);
                Err(anyhow!("图片上传失败: {}", e))
            }
        }
    }

    /// 将S3 URL转换为可访问的CDN地址
    fn convert_s3_to_cdn_url(s3_url: &str) -> String {
        // 将 s3://ap-northeast-2/modal-media-cache/ 替换为 https://cdn.roasmax.cn/
        if s3_url.starts_with("s3://ap-northeast-2/modal-media-cache/") {
            s3_url.replace("s3://ap-northeast-2/modal-media-cache/", "https://cdn.roasmax.cn/")
        } else {
            // 如果不是预期的S3格式，返回原URL
            s3_url.to_string()
        }
    }
}

/// 视频生成统计信息
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VideoGenerationStatistics {
    pub total: usize,
    pub pending: usize,
    pub processing: usize,
    pub completed: usize,
    pub failed: usize,
    pub cancelled: usize,
    pub total_videos: usize,
    pub avg_generation_time: u64,
}
