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.web.bind.annotation.DeleteMapping;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.model.ImageToVideoTask;
import com.example.demo.service.ImageToVideoService;
import com.example.demo.util.JwtUtils;

/**
 * 图生视频API控制器
 */
@RestController
@RequestMapping("/api/image-to-video")
public class ImageToVideoApiController {

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

    @Autowired
    private ImageToVideoService imageToVideoService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 创建图生视频任务
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createTask(
            @RequestParam("firstFrame") MultipartFile firstFrame,
            @RequestParam(value = "lastFrame", required = false) MultipartFile lastFrame,
            @RequestParam("prompt") String prompt,
            @RequestParam(value = "aspectRatio", defaultValue = "16:9") String aspectRatio,
            @RequestParam(value = "duration", defaultValue = "5") int duration,
            @RequestParam(value = "hdMode", defaultValue = "false") boolean hdMode,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录或token无效");
                logger.warn("图生视频API调用失败: token无效, token={}", token);
                return ResponseEntity.status(401).body(response);
            }
            
            logger.info("图生视频API调用: username={}, prompt={}", username, prompt);

            // 验证文件
            if (firstFrame.isEmpty()) {
                response.put("success", false);
                response.put("message", "请上传首帧图片");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件大小（最大100MB，与文件上传配置保持一致）
            long maxFileSize = 100 * 1024 * 1024; // 100MB
            if (firstFrame.getSize() > maxFileSize) {
                response.put("success", false);
                response.put("message", "首帧图片大小不能超过100MB");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (lastFrame != null && !lastFrame.isEmpty() && lastFrame.getSize() > maxFileSize) {
                response.put("success", false);
                response.put("message", "尾帧图片大小不能超过100MB");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证文件类型
            if (!isValidImageFile(firstFrame) || (lastFrame != null && !isValidImageFile(lastFrame))) {
                response.put("success", false);
                response.put("message", "请上传有效的图片文件（JPG、PNG、WEBP）");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证参数范围
            if (duration < 1 || duration > 60) {
                response.put("success", false);
                response.put("message", "视频时长必须在1-60秒之间");
                return ResponseEntity.badRequest().body(response);
            }

            if (!isValidAspectRatio(aspectRatio)) {
                response.put("success", false);
                response.put("message", "不支持的视频比例");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建任务
            logger.info("开始创建图生视频任务: username={}, prompt={}, aspectRatio={}, duration={}", 
                username, prompt, aspectRatio, duration);
            
            ImageToVideoTask task = imageToVideoService.createTask(
                username, firstFrame, lastFrame, prompt, aspectRatio, duration, hdMode
            );

            response.put("success", true);
            response.put("message", "任务创建成功");
            response.put("data", task);
            
            logger.info("用户 {} 创建图生视频任务成功: {}", username, task.getId());
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("创建图生视频任务失败", e);
            response.put("success", false);
            response.put("message", "创建任务失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 通过图片URL创建图生视频任务（用于"做同款"功能）
     */
    @PostMapping("/create-by-url")
    public ResponseEntity<Map<String, Object>> createTaskByUrl(
            @RequestBody Map<String, Object> request,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录或token无效");
                return ResponseEntity.status(401).body(response);
            }
            
            // 提取参数
            String imageUrl = (String) request.get("imageUrl");
            String prompt = (String) request.get("prompt");
            String aspectRatio = (String) request.getOrDefault("aspectRatio", "16:9");
            int duration = request.get("duration") instanceof Number 
                ? ((Number) request.get("duration")).intValue() 
                : Integer.parseInt(request.getOrDefault("duration", "5").toString());
            boolean hdMode = Boolean.parseBoolean(request.getOrDefault("hdMode", "false").toString());
            
            logger.info("通过URL创建图生视频任务: username={}, imageUrl={}, prompt={}", 
                username, imageUrl != null ? imageUrl.substring(0, Math.min(50, imageUrl.length())) : "null", prompt);
            
            // 验证参数
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "图片URL不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (prompt == null || prompt.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "描述文字不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (duration < 1 || duration > 60) {
                response.put("success", false);
                response.put("message", "视频时长必须在1-60秒之间");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (!isValidAspectRatio(aspectRatio)) {
                response.put("success", false);
                response.put("message", "不支持的视频比例");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 创建任务
            ImageToVideoTask task = imageToVideoService.createTaskByUrl(
                username, imageUrl.trim(), prompt.trim(), aspectRatio, duration, hdMode
            );
            
            response.put("success", true);
            response.put("message", "任务创建成功");
            response.put("data", task);
            
            logger.info("用户 {} 通过URL创建图生视频任务成功: {}", username, task.getId());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("通过URL创建图生视频任务失败", e);
            response.put("success", false);
            response.put("message", "创建任务失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取用户的任务列表
     */
    @GetMapping("/tasks")
    public ResponseEntity<Map<String, Object>> getUserTasks(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<ImageToVideoTask> tasks = imageToVideoService.getUserTasks(username, page, size);
            long totalCount = imageToVideoService.getUserTaskCount(username);

            response.put("success", true);
            response.put("data", tasks);
            response.put("total", totalCount);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取用户任务列表失败", e);
            response.put("success", false);
            response.put("message", "获取任务列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/tasks/{taskId}")
    public ResponseEntity<Map<String, Object>> getTaskDetail(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            ImageToVideoTask task = imageToVideoService.getTaskById(taskId);
            if (task == null) {
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查权限
            if (task.getUsername() == null || !task.getUsername().equals(username)) {
                response.put("success", false);
                response.put("message", "无权限访问此任务");
                return ResponseEntity.status(403).body(response);
            }

            response.put("success", true);
            response.put("data", task);
            
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取任务详情失败", e);
            response.put("success", false);
            response.put("message", "获取任务详情失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }


    /**
     * 获取任务状态
     */
    @GetMapping("/tasks/{taskId}/status")
    public ResponseEntity<Map<String, Object>> getTaskStatus(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            ImageToVideoTask task = imageToVideoService.getTaskById(taskId);
            if (task == null) {
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查权限
            if (task.getUsername() == null || !task.getUsername().equals(username)) {
                response.put("success", false);
                response.put("message", "无权限访问此任务");
                return ResponseEntity.status(403).body(response);
            }
            
            // 状态同步已通过数据库触发器实现，无需代码检查

            response.put("success", true);
            Map<String, Object> taskData = new HashMap<>();
            taskData.put("id", task.getId());
            taskData.put("status", task.getStatus());
            taskData.put("progress", task.getProgress());
            taskData.put("resultUrl", task.getResultUrl());
            taskData.put("errorMessage", task.getErrorMessage());
            response.put("data", taskData);
            
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取任务状态失败", e);
            response.put("success", false);
            response.put("message", "获取任务状态失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }

    /**
     * 验证图片文件
     */
    private boolean isValidImageFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        
        String contentType = file.getContentType();
        return contentType != null && (
            contentType.equals("image/jpeg") ||
            contentType.equals("image/png") ||
            contentType.equals("image/webp") ||
            contentType.equals("image/jpg")
        );
    }

    /**
     * 验证视频比例
     */
    private boolean isValidAspectRatio(String aspectRatio) {
        if (aspectRatio == null || aspectRatio.trim().isEmpty()) {
            return false;
        }
        
        String[] validRatios = {"16:9", "4:3", "1:1", "3:4", "9:16"};
        for (String ratio : validRatios) {
            if (ratio.equals(aspectRatio.trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 重试失败的图生视频任务
     * 复用原task_id和已上传的图片，重新提交至外部API
     */
    @PostMapping("/tasks/{taskId}/retry")
    public ResponseEntity<Map<String, Object>> retryTask(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录或token无效");
                return ResponseEntity.status(401).body(response);
            }
            
            logger.info("收到重试任务请求: taskId={}, username={}", taskId, username);
            
            // 调用重试服务
            ImageToVideoTask task = imageToVideoService.retryTask(taskId, username);
            
            response.put("success", true);
            response.put("message", "重试任务已提交");
            response.put("data", task);
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            logger.error("重试任务失败: taskId={}, error={}", taskId, e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            logger.error("重试任务异常: taskId={}", taskId, e);
            response.put("success", false);
            response.put("message", "重试任务失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/tasks/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteTask(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录或token无效");
                return ResponseEntity.status(401).body(response);
            }
            
            logger.info("删除图生视频任务: taskId={}, username={}", taskId, username);
            
            // 删除任务
            boolean deleted = imageToVideoService.deleteTask(taskId, username);
            
            if (deleted) {
                response.put("success", true);
                response.put("message", "任务删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "任务不存在或无权删除");
                return ResponseEntity.status(404).body(response);
            }
            
        } catch (Exception e) {
            logger.error("删除图生视频任务失败: taskId={}", taskId, e);
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}