package top.gtb520.java.pve_back_api.route.pve;

import it.corsinvest.proxmoxve.api.*;
import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.bind.annotation.RestController;

// 导入配置变量
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static top.gtb520.java.pve_back_api.config.AppConfig.*;

/**
 * PVE状态相关路由处理器
 * 提供与Proxmox VE服务器通信的客户端创建功能和状态查询
 */
@RestController
public class status {
    
    private static final int DEFAULT_TIMEOUT = 120000; // 2分钟超时时间

    /**
     * API：/api/pve/status
     * 类型：GET
     * 获取PVE集群状态信息，包括节点、虚拟机、容器等资源状态
     * 
     * @return 包含集群状态信息的列表
     * @throws Exception 当获取状态失败时抛出
     */
    @GetMapping("/api/pve/status")
    public List<Map<String, Object>> GetPveStatus() throws Exception {
        System.out.println("开始获取PVE状态信息...");
        List<Map<String, Object>> pveStatus = new ArrayList<>();
        
        try {
            // 创建PVE客户端
            PveClient client = createClient();
            
            // 获取集群资源信息
            var resourcesResult = client.getCluster().getResources().resources();
            
            if (resourcesResult.isSuccessStatusCode()) {
                JsonNode resources = resourcesResult.getResponse().get("data");
                
                // 统计各类资源
                int nodeCount = 0, vmCount = 0, ctCount = 0;
                int runningNodes = 0, runningVms = 0, runningCts = 0;
                
                // 处理每个资源
                for (JsonNode resource : resources) {
                    String type = resource.get("type").asText();
                    String status = resource.get("status").asText();
                    
                    Map<String, Object> resourceInfo = new HashMap<>();
                    resourceInfo.put("type", type);
                    resourceInfo.put("status", status);
                    
                    switch (type) {
                        case "node":
                            nodeCount++;
                            if ("online".equals(status)) runningNodes++;
                            resourceInfo.put("name", resource.get("node").asText());
                            resourceInfo.put("cpu_usage", String.format("%.2f%%", 
                                resource.get("cpu").asDouble() * 100));
                            resourceInfo.put("memory_usage", String.format("%.2f%%",
                                (resource.get("mem").asDouble() / resource.get("maxmem").asDouble()) * 100));
                            resourceInfo.put("uptime", formatUptime(resource.get("uptime").asInt()));
                            break;
                            
                        case "qemu":
                            vmCount++;
                            if ("running".equals(status)) runningVms++;
                            resourceInfo.put("vmid", resource.get("vmid").asInt());
                            resourceInfo.put("name", resource.get("name").asText());
                            resourceInfo.put("node", resource.get("node").asText());
                            break;
                            
                        case "lxc":
                            ctCount++;
                            if ("running".equals(status)) runningCts++;
                            resourceInfo.put("vmid", resource.get("vmid").asInt());
                            resourceInfo.put("name", resource.get("name").asText());
                            resourceInfo.put("node", resource.get("node").asText());
                            break;
                    }
                    
                    pveStatus.add(resourceInfo);
                }
                
                // 添加统计信息
                Map<String, Object> summary = new HashMap<>();
                summary.put("summary", true);
                summary.put("total_nodes", nodeCount);
                summary.put("running_nodes", runningNodes);
                summary.put("total_vms", vmCount);
                summary.put("running_vms", runningVms);
                summary.put("total_containers", ctCount);
                summary.put("running_containers", runningCts);
                summary.put("timestamp", System.currentTimeMillis());
                pveStatus.add(summary);
                
                System.out.println("✅ 成功获取PVE状态信息");
                System.out.printf("📊 统计: 节点%d(%d运行), VM%d(%d运行), 容器%d(%d运行)%n",
                    nodeCount, runningNodes, vmCount, runningVms, ctCount, runningCts);
                
            } else {
                // 更安全的错误处理
                String errorMsg = "未知错误";
                try {
                    if (resourcesResult != null) {
                        errorMsg = resourcesResult.getError();
                    } else {
                        errorMsg = "API调用返回null结果";
                    }
                } catch (Exception e) {
                    errorMsg = "错误处理异常: " + e.getClass().getSimpleName() + " - " + e.getMessage();
                }
                throw new Exception("获取集群资源失败: " + errorMsg);
            }
            
        } catch (Exception e) {
            System.err.println("❌ 获取PVE状态失败: " + e.getMessage());
            throw new Exception("获取PVE状态失败: " + e.getMessage(), e);
        }
        
        return pveStatus;
    }

    /**
     * 格式化运行时间
     */
    private static String formatUptime(int seconds) {
        int days = seconds / 86400;
        int hours = (seconds % 86400) / 3600;
        int minutes = (seconds % 3600) / 60;
        
        StringBuilder sb = new StringBuilder();
        if (days > 0) sb.append(days).append("天 ");
        if (hours > 0) sb.append(hours).append("小时 ");
        if (minutes > 0) sb.append(minutes).append("分钟");
        
        return sb.toString().trim();
    }

    /**
     * 创建PVE客户端实例
     * 支持API令牌认证和传统登录认证两种方式
     *
     * @return 配置好的PveClient实例
     * @throws RuntimeException 当客户端创建失败时抛出
     */
    public static PveClient createClient() throws RuntimeException {
        // 构建API_TOKEN字符串
        String[] api_token_list = PVE_API_TOKEN_ID.split("!");
        String api_token = api_token_list[0] + ":" + api_token_list[1] + "@" + "token=" + PVE_API_TOKEN_SECRET;
        System.out.println("API_TOKEN: " + api_token);

        // 创建PVE客户端实例
        var client = new PveClient(PVE_HOSTNAME_IP, Integer.parseInt(PVE_PORT));
        client.setValidateCertificate(false); // SSL证书验证
        client.setTimeout(DEFAULT_TIMEOUT);   // 设置请求超时时间
        client.setApiToken(api_token);
        return client;
    }
}