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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.TaskStatus;
import com.example.demo.model.User;
import com.example.demo.model.enums.CommonTaskType;
import com.example.demo.repository.TaskStatusRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.TaskStatusPollingService;
import com.example.demo.util.JwtUtils;

@RestController
@RequestMapping("/api/task-status")
@CrossOrigin(origins = "http://localhost:5173")
public class TaskStatusApiController {

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

    @Autowired
    private TaskStatusPollingService taskStatusPollingService;

    @Autowired
    private TaskStatusRepository taskStatusRepository;

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private com.example.demo.repository.StoryboardVideoTaskRepository storyboardVideoTaskRepository;
    
    /**
     * 获取任务状态
     */
    @GetMapping("/{taskId}")
    public ResponseEntity<Map<String, Object>> getTaskStatus(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 从token中提取用户名（这里简化处理，实际应该解析JWT）
            String username = extractUsernameFromToken(token);
            
            TaskStatus taskStatus = taskStatusPollingService.getTaskStatus(taskId);
            
            if (taskStatus == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 检查权限
            if (!taskStatus.getUsername().equals(username)) {
                return ResponseEntity.status(403).body(Map.of("error", "无权访问此任务"));
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("taskId", taskStatus.getTaskId());
            response.put("status", taskStatus.getStatus().name());
            response.put("statusDescription", taskStatus.getStatus().getDescription());
            response.put("progress", taskStatus.getProgress());
            response.put("resultUrl", taskStatus.getResultUrl());
            response.put("errorMessage", taskStatus.getErrorMessage());
            response.put("createdAt", taskStatus.getCreatedAt());
            response.put("updatedAt", taskStatus.getUpdatedAt());
            response.put("completedAt", taskStatus.getCompletedAt());
            response.put("pollCount", taskStatus.getPollCount());
            response.put("maxPolls", taskStatus.getMaxPolls());
            
            // 如果是分镜视频任务，额外返回 videoPrompt、imagePrompt、shotList
            if (taskId.startsWith("sb_")) {
                try {
                    storyboardVideoTaskRepository.findByTaskId(taskId).ifPresent(storyboardTask -> {
                        response.put("videoPrompt", storyboardTask.getVideoPrompt());
                        response.put("imagePrompt", storyboardTask.getImagePrompt());
                        response.put("shotList", storyboardTask.getShotList());
                    });
                } catch (Exception e) {
                    logger.warn("获取分镜视频任务额外信息失败: taskId={}, error={}", taskId, e.getMessage());
                }
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取任务状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 获取用户的所有任务状态
     */
    @GetMapping("/user/{username}")
    public ResponseEntity<List<TaskStatus>> getUserTaskStatuses(
            @PathVariable String username,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 验证token中的用户名
            String tokenUsername = extractUsernameFromToken(token);
            if (!tokenUsername.equals(username)) {
                return ResponseEntity.status(403).build();
            }
            
            List<TaskStatus> taskStatuses = taskStatusPollingService.getUserTaskStatuses(username);
            return ResponseEntity.ok(taskStatuses);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }
    
    /**
     * 取消任务
     */
    @PostMapping("/{taskId}/cancel")
    public ResponseEntity<Map<String, Object>> cancelTask(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        try {
            String username = extractUsernameFromToken(token);
            
            boolean cancelled = taskStatusPollingService.cancelTask(taskId, username);
            
            Map<String, Object> response = new HashMap<>();
            if (cancelled) {
                response.put("success", true);
                response.put("message", "任务已取消");
            } else {
                response.put("success", false);
                response.put("message", "任务取消失败，可能任务已完成或不存在");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "取消任务失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 手动触发轮询（管理员功能）
     */
    @PostMapping("/poll")
    public ResponseEntity<Map<String, Object>> triggerPolling(
            @RequestHeader("Authorization") String token) {

        try {
            // 验证token但不使用用户名（管理员接口）
            extractUsernameFromToken(token);

            // 这里可以添加管理员权限检查
            // if (!isAdmin(username)) {
            //     return ResponseEntity.status(403).body(Map.of("error", "权限不足"));
            // }

            taskStatusPollingService.pollTaskStatuses();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "轮询已触发");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "触发轮询失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取所有任务记录（管理员功能）
     */
    @GetMapping("/admin/all")
    public ResponseEntity<Map<String, Object>> getAllTaskRecords(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String taskType,
            @RequestParam(required = false) String search) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 验证token
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "未授权访问");
                return ResponseEntity.status(401).body(response);
            }

            // TODO: 添加管理员权限检查
            // if (!isAdmin(username)) {
            //     response.put("success", false);
            //     response.put("message", "权限不足");
            //     return ResponseEntity.status(403).body(response);
            // }

            // 输入验证
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            // 创建分页对象
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<TaskStatus> taskPage;

            // 根据条件查询
            if (status != null && !status.isEmpty() && !"all".equals(status)) {
                try {
                    TaskStatus.Status statusEnum = TaskStatus.Status.valueOf(status.toUpperCase());
                    taskPage = taskStatusRepository.findByStatus(statusEnum, pageable);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的任务状态: {}", status);
                    taskPage = taskStatusRepository.findAllWithPagination(pageable);
                }
            } else if (taskType != null && !taskType.isEmpty()) {
                try {
                    CommonTaskType taskTypeEnum = CommonTaskType.valueOf(taskType.toUpperCase());
                    taskPage = taskStatusRepository.findByTaskType(taskTypeEnum, pageable);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的任务类型: {}", taskType);
                    taskPage = taskStatusRepository.findAllWithPagination(pageable);
                }
            } else {
                taskPage = taskStatusRepository.findAllWithPagination(pageable);
            }

            // 构建响应数据
            List<Map<String, Object>> taskRecords = taskPage.getContent().stream()
                .map(task -> {
                    Map<String, Object> record = new HashMap<>();
                    record.put("id", task.getId());
                    record.put("taskId", task.getTaskId());
                    
                    // 通过存储的用户名查询真实的系统用户名
                    // 先尝试按 username 查找，如果找不到再按 nickname 查找
                    String storedValue = task.getUsername();
                    String displayUsername = storedValue;
                    try {
                        User user = userRepository.findByUsername(storedValue).orElse(null);
                        if (user == null) {
                            // 尝试按昵称查找
                            user = userRepository.findByNickname(storedValue).orElse(null);
                        }
                        if (user != null) {
                            displayUsername = user.getUsername();
                        }
                    } catch (Exception e) {
                        logger.debug("查询用户失败: {}", storedValue);
                    }
                    record.put("username", displayUsername);
                    record.put("type", task.getTaskType() != null ? task.getTaskType().getDescription() : "未知");
                    record.put("taskType", task.getTaskType() != null ? task.getTaskType().name() : null);
                    record.put("status", task.getStatus().name());
                    record.put("statusText", task.getStatus().getDescription());
                    record.put("progress", task.getProgress());
                    record.put("resultUrl", task.getResultUrl());
                    record.put("errorMessage", task.getErrorMessage());
                    record.put("createdAt", task.getCreatedAt());
                    record.put("updatedAt", task.getUpdatedAt());
                    record.put("completedAt", task.getCompletedAt());

                    // 计算消耗资源（根据任务类型）- 统一30积分
                    String resources = "0积分";
                    if (task.getTaskType() != null) {
                        switch (task.getTaskType()) {
                            case TEXT_TO_VIDEO:
                                resources = "30积分";
                                break;
                            case IMAGE_TO_VIDEO:
                                resources = "30积分";
                                break;
                            case STORYBOARD_VIDEO:
                                resources = "30积分";
                                break;
                            case STORYBOARD_IMAGE:
                                resources = "30积分";
                                break;
                        }
                    }
                    record.put("resources", resources);

                    return record;
                })
                .toList();

            response.put("success", true);
            response.put("data", taskRecords);
            response.put("totalElements", taskPage.getTotalElements());
            response.put("totalPages", taskPage.getTotalPages());
            response.put("currentPage", 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);
        }
    }

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


