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.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.RequestHeader;
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.TextToVideoTask;
import com.example.demo.service.TextToVideoService;
import com.example.demo.util.JwtUtils;

/**
 * 文生视频API控制器
 */
@RestController
@RequestMapping("/api/text-to-video")
public class TextToVideoApiController {

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

    @Autowired
    private TextToVideoService textToVideoService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 创建文生视频任务
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createTask(
            @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", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 获取请求参数
            String prompt = (String) request.get("prompt");
            String aspectRatio = (String) request.getOrDefault("aspectRatio", "16:9");
            
            // 安全的类型转换
            Integer duration = 5; // 默认值
            try {
                Object durationObj = request.getOrDefault("duration", 5);
                if (durationObj instanceof Integer) {
                    duration = (Integer) durationObj;
                } else if (durationObj instanceof String) {
                    duration = Integer.parseInt((String) durationObj);
                }
            } catch (NumberFormatException e) {
                duration = 5; // 使用默认值
            }
            
            Boolean hdMode = false; // 默认值
            try {
                Object hdModeObj = request.getOrDefault("hdMode", false);
                if (hdModeObj instanceof Boolean) {
                    hdMode = (Boolean) hdModeObj;
                } else if (hdModeObj instanceof String) {
                    hdMode = Boolean.parseBoolean((String) hdModeObj);
                }
            } catch (Exception e) {
                hdMode = false; // 使用默认值
            }

            // 验证参数
            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);
            }

            // 创建任务
            TextToVideoTask task = textToVideoService.createTask(
                username, prompt.trim(), aspectRatio, duration, hdMode
            );
            
            response.put("success", true);
            response.put("message", "文生视频任务创建成功");
            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")
    public ResponseEntity<Map<String, Object>> getTasks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @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);
            }
            
            List<TextToVideoTask> tasks = textToVideoService.getUserTasks(username, page, size);
            long totalCount = textToVideoService.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);
            }
            
            TextToVideoTask task = textToVideoService.getTaskByIdAndUsername(taskId, username);
            if (task == null) {
                response.put("success", false);
                response.put("message", "任务不存在或无权限访问");
                return ResponseEntity.status(404).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);
            }
            
            TextToVideoTask task = textToVideoService.getTaskByIdAndUsername(taskId, username);
            if (task == null) {
                response.put("success", false);
                response.put("message", "任务不存在或无权限访问");
                return ResponseEntity.status(404).body(response);
            }
            
            // 状态同步已通过数据库触发器实现，无需代码检查
            
            Map<String, Object> statusData = new HashMap<>();
            statusData.put("taskId", task.getTaskId());
            statusData.put("status", task.getStatus());
            statusData.put("progress", task.getProgress());
            statusData.put("resultUrl", task.getResultUrl());
            statusData.put("errorMessage", task.getErrorMessage());

            response.put("success", true);
            response.put("data", statusData);
            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);
        }
    }


    /**
     * 重试失败的文生视频任务
     * 复用原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);
            
            // 调用重试服务
            TextToVideoTask task = textToVideoService.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);
        }
    }

    /**
     * 从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 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;
    }
}
