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 {
            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");

            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
            );

            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);
            e.printStackTrace(); // 打印完整堆栈
            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("errorMessage", task.getErrorMessage());
            taskData.put("createdAt", task.getCreatedAt());
            taskData.put("updatedAt", task.getUpdatedAt());
            taskData.put("completedAt", task.getCompletedAt());

            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", "查询失败"));
        }
    }
}
