package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.StoryboardVideoTask;
import com.example.demo.service.StoryboardVideoService;

@RestController
@RequestMapping("/api/storyboard-video")
public class StoryboardVideoApiController {

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

    @Autowired
    private StoryboardVideoService storyboardVideoService;

    /**
     * 创建分镜视频任务
     */
    @PostMapping("/create")
    public ResponseEntity<?> createTask(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        try {
            // 检查用户是否已认证
            if (authentication == null) {
                logger.warn("创建分镜视频任务失败: 用户未登录");
                return ResponseEntity.status(401)
                    .body(Map.of("success", false, "message", "用户未登录，请先登录"));
            }
            String username = authentication.getName();
            logger.info("收到创建分镜视频任务请求，用户: {}", username);

            // 从请求中提取参数
            String prompt = (String) request.get("prompt");
            String aspectRatio = (String) request.getOrDefault("aspectRatio", "16:9");
            Boolean hdMode = (Boolean) request.getOrDefault("hdMode", false);
            String imageUrl = (String) request.get("imageUrl");
            String imageModel = (String) request.getOrDefault("imageModel", "nano-banana-2");
            
            // 提取用户上传的多张图片（新增）
            @SuppressWarnings("unchecked")
            List<String> uploadedImages = (List<String>) request.get("uploadedImages");
            
            // 提取duration参数，支持多种类型
            Integer duration = 10; // 默认10秒
            Object durationObj = request.get("duration");
            if (durationObj instanceof Number) {
                duration = ((Number) durationObj).intValue();
            } else if (durationObj instanceof String) {
                try {
                    duration = Integer.parseInt((String) durationObj);
                } catch (NumberFormatException e) {
                    logger.warn("无效的duration参数: {}, 使用默认值10", durationObj);
                }
            }
            logger.info("任务参数 - duration: {}, aspectRatio: {}, hdMode: {}, imageModel: {}, uploadedImages: {}", 
                duration, aspectRatio, hdMode, imageModel, uploadedImages != null ? uploadedImages.size() : 0);

            if (prompt == null || prompt.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "提示词不能为空"));
            }

            // 创建任务（传递上传的图片列表）
            StoryboardVideoTask task = storyboardVideoService.createTask(
                username, prompt, aspectRatio, hdMode != null && hdMode, imageUrl, duration, imageModel, uploadedImages
            );

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务创建成功");
            response.put("data", Map.of(
                "taskId", task.getTaskId(),
                "status", task.getStatus(),
                "progress", task.getProgress()
            ));

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            logger.error("参数错误: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", e.getMessage()));
        } catch (Exception e) {
            logger.error("创建分镜视频任务失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "创建任务失败: " + e.getMessage()));
        }
    }

    /**
     * 直接使用上传的分镜图创建视频任务（跳过分镜图生成）
     * 用户在STEP2上传分镜图后直接生成视频时调用
     */
    @PostMapping("/create-video-direct")
    public ResponseEntity<?> createVideoDirectly(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        try {
            // 检查用户是否已认证
            if (authentication == null) {
                logger.warn("直接创建视频任务失败: 用户未登录");
                return ResponseEntity.status(401)
                    .body(Map.of("success", false, "message", "用户未登录，请先登录"));
            }
            String username = authentication.getName();
            logger.info("收到直接创建视频任务请求，用户: {}", username);

            // 从请求中提取参数
            String storyboardImage = (String) request.get("storyboardImage"); // 用户上传的分镜图
            String prompt = (String) request.getOrDefault("prompt", "根据分镜图生成视频");
            String aspectRatio = (String) request.getOrDefault("aspectRatio", "16:9");
            Boolean hdMode = (Boolean) request.getOrDefault("hdMode", false);
            
            // 提取视频参考图
            @SuppressWarnings("unchecked")
            List<String> referenceImages = (List<String>) request.get("referenceImages");
            
            // 提取duration参数
            Integer duration = 10;
            Object durationObj = request.get("duration");
            if (durationObj instanceof Number) {
                duration = ((Number) durationObj).intValue();
            } else if (durationObj instanceof String) {
                try {
                    duration = Integer.parseInt((String) durationObj);
                } catch (NumberFormatException e) {
                    logger.warn("无效的duration参数: {}, 使用默认值10", durationObj);
                }
            }

            if (storyboardImage == null || storyboardImage.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "分镜图不能为空"));
            }

            logger.info("直接创建视频任务参数 - duration: {}, aspectRatio: {}, hdMode: {}, referenceImages: {}", 
                duration, aspectRatio, hdMode, referenceImages != null ? referenceImages.size() : 0);

            // 调用服务层方法直接创建视频任务
            StoryboardVideoTask task = storyboardVideoService.createVideoDirectTask(
                username, prompt, storyboardImage, aspectRatio, hdMode != null && hdMode, duration, referenceImages
            );

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "视频任务创建成功");
            response.put("data", Map.of(
                "taskId", task.getTaskId(),
                "status", task.getStatus(),
                "progress", task.getProgress()
            ));

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            logger.error("参数错误: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", e.getMessage()));
        } catch (Exception e) {
            logger.error("直接创建视频任务失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "创建任务失败: " + e.getMessage()));
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/task/{taskId}")
    public ResponseEntity<?> getTask(@PathVariable String taskId, Authentication authentication) {
        try {
            String username = authentication.getName();
            logger.info("收到获取分镜视频任务详情请求，任务ID: {}, 用户: {}", taskId, username);

            StoryboardVideoTask task = storyboardVideoService.getTask(taskId);
            
            // 验证用户权限
            if (!task.getUsername().equals(username)) {
                logger.warn("用户 {} 尝试访问任务 {}，但任务属于用户 {}", username, taskId, task.getUsername());
                return ResponseEntity.status(403)
                    .body(Map.of("success", false, "message", "无权访问此任务"));
            }
            
            // 状态同步已通过数据库触发器实现，无需代码检查
            
            Map<String, Object> taskData = new HashMap<>();
            taskData.put("taskId", task.getTaskId());
            taskData.put("status", task.getStatus());
            taskData.put("progress", task.getProgress());
            taskData.put("resultUrl", task.getResultUrl());
            taskData.put("videoUrls", task.getVideoUrls()); // 视频URL（JSON数组）
            taskData.put("imageUrl", task.getImageUrl()); // 参考图片（旧字段）
            taskData.put("uploadedImages", task.getUploadedImages()); // 用户上传的参考图（JSON数组）
            taskData.put("prompt", task.getPrompt());
            taskData.put("aspectRatio", task.getAspectRatio());
            taskData.put("hdMode", task.isHdMode());
            taskData.put("duration", task.getDuration());
            taskData.put("errorMessage", task.getErrorMessage());
            taskData.put("createdAt", task.getCreatedAt());
            taskData.put("updatedAt", task.getUpdatedAt());
            taskData.put("completedAt", task.getCompletedAt());
            // 大模型优化后的提示词字段
            taskData.put("shotList", task.getShotList());
            taskData.put("imagePrompt", task.getImagePrompt());
            taskData.put("videoPrompt", task.getVideoPrompt());

            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", taskData
            ));

        } catch (RuntimeException e) {
            logger.error("获取任务详情失败: {}", e.getMessage());
            return ResponseEntity.status(404)
                .body(Map.of("success", false, "message", "任务不存在"));
        } catch (Exception e) {
            logger.error("获取任务详情异常", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "查询失败"));
        }
    }

    /**
     * 获取用户任务列表
     */
    @GetMapping("/tasks")
    public ResponseEntity<?> getUserTasks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            String username = authentication.getName();
            List<StoryboardVideoTask> tasks = storyboardVideoService.getUserTasks(username, page, size);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", tasks,
                "page", page,
                "size", size
            ));

        } catch (Exception e) {
            logger.error("获取用户任务列表失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "查询失败"));
        }
    }

    /**
     * 开始生成视频（从分镜图生成视频）
     * 用户点击"开始生成"按钮后调用
     */
    @PostMapping("/task/{taskId}/start-video")
    public ResponseEntity<?> startVideoGeneration(
            @PathVariable String taskId,
            @RequestBody(required = false) Map<String, Object> requestBody,
            Authentication authentication) {
        try {
            String username = authentication.getName();
            logger.info("收到开始生成视频请求，任务ID: {}, 用户: {}", taskId, username);

            // 验证任务是否存在且属于该用户
            StoryboardVideoTask task = storyboardVideoService.getTask(taskId);
            if (!task.getUsername().equals(username)) {
                logger.warn("用户 {} 尝试访问任务 {}，但任务属于用户 {}", username, taskId, task.getUsername());
                return ResponseEntity.status(403)
                    .body(Map.of("success", false, "message", "无权访问此任务"));
            }

            // 从请求体中提取参数（如果有）
            Integer duration = null;
            String aspectRatio = null;
            Boolean hdMode = null;
            java.util.List<String> referenceImages = null;
            String storyboardImage = null; // 前端传递的分镜图URL
            
            if (requestBody != null) {
                if (requestBody.containsKey("duration")) {
                    Object durationObj = requestBody.get("duration");
                    if (durationObj instanceof Number) {
                        duration = ((Number) durationObj).intValue();
                    } else if (durationObj instanceof String) {
                        duration = Integer.parseInt((String) durationObj);
                    }
                    logger.info("视频时长参数: {}", duration);
                }
                if (requestBody.containsKey("aspectRatio")) {
                    aspectRatio = (String) requestBody.get("aspectRatio");
                    logger.info("视频宽高比参数: {}", aspectRatio);
                }
                if (requestBody.containsKey("hdMode")) {
                    hdMode = (Boolean) requestBody.get("hdMode");
                    logger.info("高清模式参数: {}", hdMode);
                }
                if (requestBody.containsKey("referenceImages")) {
                    Object refImagesObj = requestBody.get("referenceImages");
                    if (refImagesObj instanceof java.util.List) {
                        referenceImages = (java.util.List<String>) refImagesObj;
                        logger.info("参考图数量: {}", referenceImages.size());
                    }
                }
                if (requestBody.containsKey("storyboardImage")) {
                    storyboardImage = (String) requestBody.get("storyboardImage");
                    logger.info("前端传递的分镜图URL: {}", storyboardImage != null ? storyboardImage.substring(0, Math.min(80, storyboardImage.length())) + "..." : "null");
                } else {
                    logger.warn("请求体中没有storyboardImage参数，requestBody keys: {}", requestBody.keySet());
                }
            } else {
                logger.warn("请求体为空");
            }

            logger.info("调用startVideoGeneration: taskId={}, storyboardImage={}", taskId, 
                storyboardImage != null ? "有值(长度:" + storyboardImage.length() + ")" : "null");
            
            // 开始生成视频，传递参数（包括参考图和分镜图URL）
            storyboardVideoService.startVideoGeneration(taskId, duration, aspectRatio, hdMode, referenceImages, storyboardImage);

            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "视频生成任务已启动"
            ));

        } catch (RuntimeException e) {
            logger.error("开始生成视频失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", e.getMessage()));
        } catch (Exception e) {
            logger.error("开始生成视频异常", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "启动视频生成失败"));
        }
    }

    /**
     * 重试失败的分镜视频任务
     */
    @PostMapping("/task/{taskId}/retry")
    public ResponseEntity<?> retryTask(
            @PathVariable String taskId,
            Authentication authentication) {
        
        logger.info("收到重试任务请求，任务ID: {}", taskId);
        
        try {
            // 检查用户是否已认证
            if (authentication == null) {
                return ResponseEntity.status(401)
                    .body(Map.of("success", false, "message", "请先登录"));
            }
            String username = authentication.getName();

            // 验证任务是否存在且属于该用户
            StoryboardVideoTask task = storyboardVideoService.getTask(taskId);
            if (!task.getUsername().equals(username)) {
                logger.warn("用户 {} 尝试重试任务 {}，但任务属于用户 {}", username, taskId, task.getUsername());
                return ResponseEntity.status(403)
                    .body(Map.of("success", false, "message", "无权操作此任务"));
            }
            
            // 验证任务状态必须是 FAILED
            if (task.getStatus() != StoryboardVideoTask.TaskStatus.FAILED) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "只能重试失败的任务"));
            }

            // 调用重试服务
            storyboardVideoService.retryTask(taskId);

            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "重试任务已提交",
                "data", Map.of("taskId", taskId)
            ));

        } catch (RuntimeException e) {
            logger.error("重试任务失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", e.getMessage()));
        } catch (Exception e) {
            logger.error("重试任务异常", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "重试任务失败"));
        }
    }
}
