package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.demo.model.StoryboardVideoTask;
import com.example.demo.repository.StoryboardVideoTaskRepository;

/**
 * 分镜视频服务类
 */
@Service
@Transactional
public class StoryboardVideoService {

    private static final Logger logger = LoggerFactory.getLogger(StoryboardVideoService.class);

    @Autowired
    private StoryboardVideoTaskRepository taskRepository;

    @Autowired
    private RealAIService realAIService;

    @Autowired
    private ImageGridService imageGridService;
    
    // 默认生成6张分镜图
    private static final int DEFAULT_STORYBOARD_IMAGES = 6;

    /**
     * 创建分镜视频任务
     */
    public StoryboardVideoTask createTask(String username, String prompt, String aspectRatio, boolean hdMode, String imageUrl) {
        try {
            // 验证参数
            if (username == null || username.trim().isEmpty()) {
                throw new IllegalArgumentException("用户名不能为空");
            }
            if (prompt == null || prompt.trim().isEmpty()) {
                throw new IllegalArgumentException("文本描述不能为空");
            }
            
            // 生成任务ID
            String taskId = generateTaskId();
            
            // 创建任务
            StoryboardVideoTask task = new StoryboardVideoTask(username, prompt.trim(), aspectRatio, hdMode);
            task.setTaskId(taskId);
            task.setStatus(StoryboardVideoTask.TaskStatus.PENDING);
            task.setProgress(0);
            
            if (imageUrl != null && !imageUrl.isEmpty()) {
                task.setImageUrl(imageUrl);
            }
            
            // 保存任务
            task = taskRepository.save(task);
            
            logger.info("分镜视频任务创建成功: {}, 用户: {}", taskId, username);
            
            // 异步处理任务
            processTaskAsync(taskId);
            
            return task;
            
        } catch (Exception e) {
            logger.error("创建分镜视频任务失败", e);
            throw new RuntimeException("创建任务失败: " + e.getMessage());
        }
    }

    /**
     * 使用真实API处理任务（异步）
     * 使用Spring的@Async注解，自动管理事务边界
     */
    @Async
    @Transactional
    public void processTaskAsync(String taskId) {
        try {
            logger.info("开始使用真实API处理分镜视频任务: {}", taskId);
            
            // 重新从数据库加载任务，获取最新状态
            StoryboardVideoTask task = taskRepository.findByTaskId(taskId)
                .orElseThrow(() -> new RuntimeException("任务未找到: " + taskId));
            
            // 更新任务状态为处理中
            task.updateStatus(StoryboardVideoTask.TaskStatus.PROCESSING);
            taskRepository.flush(); // 强制刷新到数据库
            
            // 调用真实文生图API，生成多张分镜图
            logger.info("分镜视频任务已提交，正在调用文生图API生成{}张分镜图...", DEFAULT_STORYBOARD_IMAGES);
            
            Map<String, Object> apiResponse = realAIService.submitTextToImageTask(
                task.getPrompt(), 
                task.getAspectRatio(),
                DEFAULT_STORYBOARD_IMAGES  // 生成多张图片用于分镜图
            );
            
            // 从API响应中提取所有图片URL
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> data = (List<Map<String, Object>>) apiResponse.get("data");
            if (data != null && !data.isEmpty()) {
                // 收集所有图片URL
                List<String> imageUrls = new ArrayList<>();
                for (Map<String, Object> imageData : data) {
                    String imageUrl = null;
                    if (imageData.get("url") != null) {
                        imageUrl = (String) imageData.get("url");
                    } else if (imageData.get("b64_json") != null) {
                        // base64编码的图片
                        String base64Data = (String) imageData.get("b64_json");
                        imageUrl = "data:image/png;base64," + base64Data;
                    }
                    if (imageUrl != null) {
                        imageUrls.add(imageUrl);
                    }
                }
                
                if (imageUrls.isEmpty()) {
                    throw new RuntimeException("未能从API响应中提取任何图片URL");
                }
                
                logger.info("成功获取{}张图片，开始拼接成分镜图网格...", imageUrls.size());
                
                // 拼接多张图片成网格
                String mergedImageUrl = imageGridService.mergeImagesToGrid(imageUrls, 0); // 0表示自动计算列数
                
                // 重新加载任务（因为之前的flush可能使实体detached）
                task = taskRepository.findByTaskId(taskId)
                    .orElseThrow(() -> new RuntimeException("任务未找到: " + taskId));
                
                // 设置拼接后的结果图片URL
                task.setResultUrl(mergedImageUrl);
                task.setRealTaskId(taskId + "_image");
                task.updateStatus(StoryboardVideoTask.TaskStatus.COMPLETED);
                task.updateProgress(100);
                
                taskRepository.save(task);
                
                logger.info("分镜图生成并拼接完成，任务ID: {}, 共生成{}张图片", taskId, imageUrls.size());
            } else {
                throw new RuntimeException("API返回的图片数据为空");
            }
            
        } catch (Exception e) {
            logger.error("处理分镜视频任务失败: {}", taskId, e);
            try {
                StoryboardVideoTask task = taskRepository.findByTaskId(taskId)
                    .orElseThrow(() -> new RuntimeException("任务未找到: " + taskId));
                task.updateStatus(StoryboardVideoTask.TaskStatus.FAILED);
                task.setErrorMessage(e.getMessage());
                taskRepository.save(task);
            } catch (Exception ex) {
                logger.error("更新任务失败状态失败: {}", taskId, ex);
            }
        }
    }

    /**
     * 获取任务详情
     */
    @Transactional(readOnly = true)
    public StoryboardVideoTask getTask(String taskId) {
        return taskRepository.findByTaskId(taskId)
            .orElseThrow(() -> new RuntimeException("任务不存在: " + taskId));
    }

    /**
     * 获取用户任务列表
     */
    @Transactional(readOnly = true)
    public List<StoryboardVideoTask> getUserTasks(String username, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<StoryboardVideoTask> taskPage = taskRepository.findByUsernameOrderByCreatedAtDesc(username, pageable);
        return taskPage.getContent();
    }

    /**
     * 生成任务ID
     */
    private String generateTaskId() {
        return "sb_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}
