/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.config
 * @ClassName: VectorizationHealthIndicator
 * @Description: 向量化服务健康检查指示器，用于Actuator健康检查
 * @Author: 张志锋
 * @Date: 2025-11-03
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.config;

import com.zhpb.gdyd_zhpb_zgf.entity.mysql.File;
import com.zhpb.gdyd_zhpb_zgf.repository.mysql.FileRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 向量化服务健康检查指示器
 */
@Component
public class VectorizationHealthIndicator implements HealthIndicator {

    private static final Logger logger = LoggerFactory.getLogger(VectorizationHealthIndicator.class);

    @Autowired
    private FileRepository fileRepository;

    @Override
    public Health health() {
        logger.debug("开始执行向量化服务健康检查");
        try {
            // 检查数据库连接和文件表
            logger.debug("查询所有文件记录");
            List<File> files = fileRepository.findAll();
            logger.debug("查询到 {} 个文件记录", files.size());

            // 统计向量化状态
            int totalFiles = files.size();
            int completedFiles = 0;
            int processingFiles = 0;
            int failedFiles = 0;
            int notStartedFiles = 0;

            LocalDateTime lastVectorizedTime = null;

            for (File file : files) {
                String status = file.getVectorizationStatus();
                if ("completed".equals(status)) {
                    completedFiles++;
                    if (lastVectorizedTime == null ||
                        (file.getVectorizedTime() != null && file.getVectorizedTime().isAfter(lastVectorizedTime))) {
                        lastVectorizedTime = file.getVectorizedTime();
                    }
                } else if ("processing".equals(status)) {
                    processingFiles++;
                } else if ("failed".equals(status)) {
                    failedFiles++;
                } else {
                    notStartedFiles++;
                }
            }

            // 计算健康状态
            // 如果有太多失败的文件，认为服务不健康
            double failureRate = totalFiles > 0 ? (double) failedFiles / totalFiles : 0.0;

            if (failureRate > 0.5) {
                // 失败率超过50%，认为服务不健康
                logger.warn("向量化服务健康检查失败：失败率过高 ({})", String.format("%.2f%%", failureRate * 100));
                return Health.down()
                        .withDetail("service", "向量化服务")
                        .withDetail("status", "健康状况异常")
                        .withDetail("total_files", totalFiles)
                        .withDetail("completed_files", completedFiles)
                        .withDetail("processing_files", processingFiles)
                        .withDetail("failed_files", failedFiles)
                        .withDetail("not_started_files", notStartedFiles)
                        .withDetail("failure_rate", String.format("%.2f%%", failureRate * 100))
                        .withDetail("error", "向量化失败率过高")
                        .build();
            } else if (processingFiles > 0) {
                // 有文件正在处理，认为是正常但有警告
                logger.info("向量化服务健康检查通过：有文件正在处理");
                return Health.up()
                        .withDetail("service", "向量化服务")
                        .withDetail("status", "正常（有文件正在处理）")
                        .withDetail("total_files", totalFiles)
                        .withDetail("completed_files", completedFiles)
                        .withDetail("processing_files", processingFiles)
                        .withDetail("failed_files", failedFiles)
                        .withDetail("not_started_files", notStartedFiles)
                        .withDetail("completion_rate", String.format("%.2f%%", totalFiles > 0 ? (double) completedFiles / totalFiles * 100 : 0))
                        .withDetail("last_vectorized", lastVectorizedTime != null ? lastVectorizedTime.toString() : "无")
                        .build();
            } else {
                // 正常状态
                logger.info("向量化服务健康检查通过：运行正常");
                return Health.up()
                        .withDetail("service", "向量化服务")
                        .withDetail("status", "运行正常")
                        .withDetail("total_files", totalFiles)
                        .withDetail("completed_files", completedFiles)
                        .withDetail("processing_files", processingFiles)
                        .withDetail("failed_files", failedFiles)
                        .withDetail("not_started_files", notStartedFiles)
                        .withDetail("completion_rate", String.format("%.2f%%", totalFiles > 0 ? (double) completedFiles / totalFiles * 100 : 0))
                        .withDetail("last_vectorized", lastVectorizedTime != null ? lastVectorizedTime.toString() : "无")
                        .build();
            }

        } catch (Exception e) {
            return Health.down()
                    .withDetail("service", "向量化服务")
                    .withDetail("status", "检查失败")
                    .withDetail("error", e.getMessage())
                    .build();
        }
    }
}
