package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import com.example.demo.model.TaskStatus;
import com.example.demo.service.TaskStatusPollingService;

@RestController
@RequestMapping("/api/task-status")
@CrossOrigin(origins = "http://localhost:5173")
public class TaskStatusApiController {
    
    @Autowired
    private TaskStatusPollingService taskStatusPollingService;
    
    /**
     * 获取任务状态
     */
    @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());
            
            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);
        }
    }
    
    /**
     * 从token中提取用户名（简化实现）
     */
    private String extractUsernameFromToken(String token) {
        // 这里应该解析JWT token，现在简化处理
        // 实际实现应该使用JWT工具类
        String cleanToken = token;
        if (token.startsWith("Bearer ")) {
            cleanToken = token.substring(7);
        }
        
        // 简化处理，实际应该解析JWT
        return "admin"; // 临时返回admin，实际应该从JWT中解析
    }
}


