package com.example.demo.controller;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
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/diagnostic")
public class QueueDiagnosticController {

    @Autowired
    private TaskQueueRepository taskQueueRepository;

    @Autowired
    private ImageToVideoTaskRepository imageToVideoTaskRepository;


    /**
     * 检查队列状态
     */
    @GetMapping("/queue-status")
    public ResponseEntity<Map<String, Object>> checkQueueStatus() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<TaskQueue> allTasks = taskQueueRepository.findAll();
            long pendingCount = allTasks.stream().filter(t -> t.getStatus() == TaskQueue.QueueStatus.PENDING).count();
            long processingCount = allTasks.stream().filter(t -> t.getStatus() == TaskQueue.QueueStatus.PROCESSING).count();
            long completedCount = allTasks.stream().filter(t -> t.getStatus() == TaskQueue.QueueStatus.COMPLETED).count();
            long failedCount = allTasks.stream().filter(t -> t.getStatus() == TaskQueue.QueueStatus.FAILED).count();
            long timeoutCount = allTasks.stream().filter(t -> t.getStatus() == TaskQueue.QueueStatus.TIMEOUT).count();
            
            response.put("success", true);
            response.put("totalTasks", allTasks.size());
            response.put("pending", pendingCount);
            response.put("processing", processingCount);
            response.put("completed", completedCount);
            response.put("failed", failedCount);
            response.put("timeout", timeoutCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查队列状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 检查图片文件是否存在
     */
    @GetMapping("/check-image/{taskId}")
    public ResponseEntity<Map<String, Object>> checkImageFile(@PathVariable String taskId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<ImageToVideoTask> taskOpt = imageToVideoTaskRepository.findByTaskId(taskId);
            if (!taskOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "找不到任务: " + taskId);
                return ResponseEntity.notFound().build();
            }
            
            ImageToVideoTask task = taskOpt.get();
            String firstFrameUrl = task.getFirstFrameUrl();
            String lastFrameUrl = task.getLastFrameUrl();
            
            Map<String, Object> imageInfo = new HashMap<>();
            
            // 检查首帧图片
            if (firstFrameUrl != null) {
                Map<String, Object> firstFrameInfo = checkImageFileExists(firstFrameUrl);
                imageInfo.put("firstFrame", firstFrameInfo);
            }
            
            // 检查尾帧图片
            if (lastFrameUrl != null) {
                Map<String, Object> lastFrameInfo = checkImageFileExists(lastFrameUrl);
                imageInfo.put("lastFrame", lastFrameInfo);
            }
            
            response.put("success", true);
            response.put("taskId", taskId);
            response.put("imageInfo", imageInfo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查图片文件失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 检查单个图片文件
     */
    private Map<String, Object> checkImageFileExists(String imageUrl) {
        Map<String, Object> result = new HashMap<>();
        result.put("url", imageUrl);
        
        try {
            if (imageUrl.startsWith("http://") || imageUrl.startsWith("https://")) {
                result.put("type", "URL");
                result.put("exists", "需要网络访问");
                return result;
            }
            
            // 检查相对路径
            Path imagePath = Paths.get(imageUrl);
            if (Files.exists(imagePath)) {
                result.put("type", "相对路径");
                result.put("exists", true);
                result.put("size", Files.size(imagePath));
                result.put("readable", Files.isReadable(imagePath));
                return result;
            }
            
            // 检查绝对路径
            String currentDir = System.getProperty("user.dir");
            Path absolutePath = Paths.get(currentDir, imageUrl);
            if (Files.exists(absolutePath)) {
                result.put("type", "绝对路径");
                result.put("exists", true);
                result.put("size", Files.size(absolutePath));
                result.put("readable", Files.isReadable(absolutePath));
                result.put("fullPath", absolutePath.toString());
                return result;
            }
            
            // 检查备用路径
            Path altPath = Paths.get("C:\\Users\\UI\\Desktop\\AIGC\\demo", imageUrl);
            if (Files.exists(altPath)) {
                result.put("type", "备用路径");
                result.put("exists", true);
                result.put("size", Files.size(altPath));
                result.put("readable", Files.isReadable(altPath));
                result.put("fullPath", altPath.toString());
                return result;
            }
            
            result.put("exists", false);
            result.put("error", "文件不存在于任何路径");
            result.put("checkedPaths", new String[]{
                imageUrl,
                absolutePath.toString(),
                altPath.toString()
            });
            
        } catch (Exception e) {
            result.put("exists", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取失败任务的详细信息
     */
    @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("/retry-task/{taskId}")
    public ResponseEntity<Map<String, Object>> retryTask(@PathVariable String taskId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<TaskQueue> taskOpt = taskQueueRepository.findByTaskId(taskId);
            if (!taskOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "找不到任务: " + taskId);
                return ResponseEntity.notFound().build();
            }
            
            TaskQueue task = taskOpt.get();
            if (task.getStatus() != TaskQueue.QueueStatus.FAILED) {
                response.put("success", false);
                response.put("message", "任务状态不是失败状态: " + task.getStatus());
                return ResponseEntity.badRequest().body(response);
            }
            
            // 重置任务状态
            task.updateStatus(TaskQueue.QueueStatus.PENDING);
            task.setErrorMessage(null);
            taskQueueRepository.save(task);
            
            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);
        }
    }
}
