package com.qqchen.deploy.backend.deploy.monitor;

import com.qqchen.deploy.backend.deploy.dto.ServerMonitorDataDTO;
import com.qqchen.deploy.backend.framework.enums.MonitorMetricEnum;
import com.qqchen.deploy.backend.framework.monitor.ServerThresholdCheckerFactory;
import com.qqchen.deploy.backend.framework.monitor.impl.CpuThresholdChecker;
import com.qqchen.deploy.backend.framework.monitor.impl.DiskThresholdChecker;
import com.qqchen.deploy.backend.framework.monitor.impl.MemoryThresholdChecker;
import com.qqchen.deploy.backend.framework.monitor.impl.NetworkThresholdChecker;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 服务器监控阈值检测器工厂
 * Deploy 业务层使用 Framework 提供的检测器能力
 *
 * @author qqchen
 * @since 2025-12-07
 */
@Component
public class ServerMonitorThresholdCheckerFactory extends ServerThresholdCheckerFactory<ServerMonitorDataDTO> {
    
    @PostConstruct
    @Override
    protected void registerCheckers() {
        // 注册 CPU 检测器
        checkers.put(MonitorMetricEnum.CPU, 
            new CpuThresholdChecker<>(ServerMonitorDataDTO::getCpuUsage));
        
        // 注册内存检测器
        checkers.put(MonitorMetricEnum.MEMORY, 
            new MemoryThresholdChecker<>(ServerMonitorDataDTO::getMemoryUsage));
        
        // 注册磁盘检测器（取所有分区中使用率最高的）
        checkers.put(MonitorMetricEnum.DISK, 
            new DiskThresholdChecker<>(data -> {
                if (data == null || data.getDiskUsage() == null || data.getDiskUsage().isEmpty()) {
                    return null;
                }
                return data.getDiskUsage().stream()
                    .map(disk -> disk.getUsagePercent())
                    .max(BigDecimal::compareTo)
                    .orElse(null);
            }));
        
        // 注册网络检测器（读取 DTO 中已计算好的速率，取 Rx 和 Tx 速率的最大值）
        checkers.put(MonitorMetricEnum.NETWORK, 
            new NetworkThresholdChecker<>(data -> {
                if (data == null) {
                    return null;
                }
                
                Long rxSpeed = data.getNetworkRxSpeed();
                Long txSpeed = data.getNetworkTxSpeed();
                
                // 如果速率都为null，返回null
                if (rxSpeed == null && txSpeed == null) {
                    return null;
                }
                
                // 取最大值（KB/s）
                long maxSpeedKBps = Math.max(
                    rxSpeed != null ? rxSpeed : 0, 
                    txSpeed != null ? txSpeed : 0
                );
                
                // 转换为 MB/s（阈值配置单位）
                return new BigDecimal(maxSpeedKBps)
                    .divide(new BigDecimal(1024), 2, RoundingMode.HALF_UP);
            }));
    }
}
