package com.example.demo.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.ImageToVideoTask;
import com.example.demo.model.TaskQueue;
import com.example.demo.repository.ImageToVideoTaskRepository;
import com.example.demo.repository.TaskQueueRepository;

/**
 * 轮询诊断控制器
 * 专门用于诊断第三次轮询查询时的错误
 */
@RestController
@RequestMapping("/api/polling-diagnostic")
public class PollingDiagnosticController {

    @Autowired
    private TaskQueueRepository taskQueueRepository;

    @Autowired
    private ImageToVideoTaskRepository imageToVideoTaskRepository;

    /**
     * 检查特定任务的轮询状态
     */
    @GetMapping("/task-status/{taskId}")
    public ResponseEntity<Map<String, Object>> checkTaskPollingStatus(@PathVariable String taskId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查任务队列状态
            Optional<TaskQueue> taskQueueOpt = taskQueueRepository.findByTaskId(taskId);
            if (!taskQueueOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "找不到任务队列: " + taskId);
                return ResponseEntity.notFound().build();
            }
            
            TaskQueue taskQueue = taskQueueOpt.get();
            
            // 检查原始任务状态
            Optional<ImageToVideoTask> imageTaskOpt = imageToVideoTaskRepository.findByTaskId(taskId);
            
            Map<String, Object> taskInfo = new HashMap<>();
            taskInfo.put("taskId", taskId);
            taskInfo.put("queueStatus", taskQueue.getStatus());
            taskInfo.put("queueErrorMessage", taskQueue.getErrorMessage());
            taskInfo.put("queueCreatedAt", taskQueue.getCreatedAt());
            taskInfo.put("queueUpdatedAt", taskQueue.getUpdatedAt());
            taskInfo.put("checkCount", taskQueue.getCheckCount());
            taskInfo.put("realTaskId", taskQueue.getRealTaskId());
            
            if (imageTaskOpt.isPresent()) {
                ImageToVideoTask imageTask = imageTaskOpt.get();
                taskInfo.put("originalStatus", imageTask.getStatus());
                taskInfo.put("originalProgress", imageTask.getProgress());
                taskInfo.put("originalErrorMessage", imageTask.getErrorMessage());
                taskInfo.put("originalCreatedAt", imageTask.getCreatedAt());
                taskInfo.put("originalUpdatedAt", imageTask.getUpdatedAt());
                taskInfo.put("firstFrameUrl", imageTask.getFirstFrameUrl());
                taskInfo.put("lastFrameUrl", imageTask.getLastFrameUrl());
            } else {
                taskInfo.put("originalStatus", "NOT_FOUND");
            }
            
            // 分析问题
            String analysis = analyzePollingIssue(taskQueue, imageTaskOpt.orElse(null));
            taskInfo.put("analysis", analysis);
            
            response.put("success", true);
            response.put("taskInfo", taskInfo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查任务轮询状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 分析轮询问题
     */
    private String analyzePollingIssue(TaskQueue taskQueue, ImageToVideoTask imageTask) {
        StringBuilder analysis = new StringBuilder();
        
        // 检查队列状态
        switch (taskQueue.getStatus()) {
            case FAILED:
                analysis.append("❌ 队列状态: FAILED - ").append(taskQueue.getErrorMessage()).append("\n");
                break;
            case TIMEOUT:
                analysis.append("❌ 队列状态: TIMEOUT - 任务处理超时\n");
                break;
            case PROCESSING:
                analysis.append("⏳ 队列状态: PROCESSING - 任务正在处理中\n");
                break;
            case COMPLETED:
                analysis.append("✅ 队列状态: COMPLETED - 任务已完成\n");
                break;
            default:
                analysis.append("❓ 队列状态: ").append(taskQueue.getStatus()).append("\n");
                break;
        }
        
        // 检查原始任务状态
        if (imageTask != null) {
            switch (imageTask.getStatus()) {
                case FAILED:
                    analysis.append("❌ 原始任务状态: FAILED - ").append(imageTask.getErrorMessage()).append("\n");
                    break;
                case COMPLETED:
                    analysis.append("✅ 原始任务状态: COMPLETED\n");
                    break;
                case PROCESSING:
                    analysis.append("⏳ 原始任务状态: PROCESSING - 进度: ").append(imageTask.getProgress()).append("%\n");
                    break;
                default:
                    analysis.append("❓ 原始任务状态: ").append(imageTask.getStatus()).append("\n");
                    break;
            }
        } else {
            analysis.append("❌ 原始任务: 未找到\n");
        }
        
        // 检查轮询次数
        int checkCount = taskQueue.getCheckCount();
        analysis.append("📊 轮询次数: ").append(checkCount).append("\n");
        
        if (checkCount >= 3) {
            analysis.append("⚠️ 已进行多次轮询，可能存在问题\n");
        }
        
        // 检查时间
        LocalDateTime now = LocalDateTime.now();
        if (taskQueue.getCreatedAt() != null) {
            long minutesSinceCreated = java.time.Duration.between(taskQueue.getCreatedAt(), now).toMinutes();
            analysis.append("⏰ 任务创建时间: ").append(minutesSinceCreated).append(" 分钟前\n");
            
            if (minutesSinceCreated > 10) {
                analysis.append("⚠️ 任务创建时间过长，可能已超时\n");
            }
        }
        
        // 检查图片文件
        if (imageTask != null && imageTask.getFirstFrameUrl() != null) {
            analysis.append("🖼️ 首帧图片: ").append(imageTask.getFirstFrameUrl()).append("\n");
        }
        
        return analysis.toString();
    }

    /**
     * 获取所有失败的任务
     */
    @GetMapping("/failed-tasks")
    public ResponseEntity<Map<String, Object>> getFailedTasks() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<TaskQueue> allTasks = taskQueueRepository.findAll();
            List<TaskQueue> failedTasks = allTasks.stream()
                .filter(t -> t.getStatus() == TaskQueue.QueueStatus.FAILED)
                .collect(java.util.stream.Collectors.toList());
            
            response.put("success", true);
            response.put("failedTasks", failedTasks);
            response.put("count", failedTasks.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取失败任务失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 重置任务状态（用于测试）
     */
    @PostMapping("/reset-task/{taskId}")
    public ResponseEntity<Map<String, Object>> resetTask(@PathVariable String taskId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<TaskQueue> taskQueueOpt = taskQueueRepository.findByTaskId(taskId);
            if (!taskQueueOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "找不到任务: " + taskId);
                return ResponseEntity.notFound().build();
            }
            
            TaskQueue taskQueue = taskQueueOpt.get();
            taskQueue.updateStatus(TaskQueue.QueueStatus.PENDING);
            taskQueue.setErrorMessage(null);
            taskQueue.setCheckCount(0);
            taskQueueRepository.save(taskQueue);
            
            response.put("success", true);
            response.put("message", "任务已重置为待处理状态");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "重置任务失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
