#!/bin/bash
################################################################################
# Nacos深度检测模块
# 功能: 深度检测Nacos服务实例、配置数量、健康状态、Raft集群等
# 作者: Claude Code
# 日期: 2026-07-20
################################################################################

# 获取脚本所在目录并加载依赖
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="${LIB_DIR:-/tmp/check_modules}"

# 加载配置文件和通用函数库
if [ -f "$LIB_DIR/lib/config.sh" ]; then
    source "$LIB_DIR/lib/config.sh"
else
    echo "ERROR: 配置文件不存在: $LIB_DIR/lib/config.sh"
    exit 1
fi

if [ -f "$LIB_DIR/lib/common.sh" ]; then
    source "$LIB_DIR/lib/common.sh"
else
    echo "ERROR: 通用函数库不存在: $LIB_DIR/lib/common.sh"
    exit 1
    exit 1
fi

# Nacos容器名称
NACOS_CONTAINER="${CONTAINERS[nacos]}"

# ==================== 辅助函数 ====================

nacos_exec() {
    docker exec "$NACOS_CONTAINER" $@ 2>/dev/null
}

nacos_api() {
    local endpoint=$1
    nacos_exec curl -s "http://localhost:8848/nacos/$endpoint" 2>/dev/null
}

# ==================== 深度检测函数 ====================

# 检测Nacos版本
check_nacos_version() {
    local nacos_version
    nacos_version=$(nacos_exec cat /home/nacos/version.txt 2>/dev/null | head -1)

    if [ -n "$nacos_version" ]; then
        output_result "NACOS_VERSION" "$nacos_version"
    else
        # 尝试从启动日志获取版本
        nacos_version=$(nacos_exec cat /home/nacos/logs/start.out 2>/dev/null | grep "Nacos" | head -1)
        [ -n "$nacos_version" ] && output_result "NACOS_VERSION" "$nacos_version"
    fi
}

# 检测Nacos服务实例统计
check_nacos_services() {
    # 获取命名空间列表
    local namespaces
    namespaces=$(nacos_api "v1/console/namespaces" 2>/dev/null)

    if [ -n "$namespaces" ]; then
        local namespace_count
        namespace_count=$(echo "$namespaces" | grep -o "namespaceId" | wc -l)
        output_result "NACOS_NAMESPACES" "$namespace_count"
    fi

    # 获取服务列表（默认命名空间）
    local services
    services=$(nacos_api "v1/ns/service/list?pageNo=1&pageSize=100&namespaceId=" 2>/dev/null)

    if [ -n "$services" ]; then
        local service_count
        service_count=$(echo "$services" | grep -o '"count":[0-9]*' | cut -d: -f2 | head -1)
        [ -n "$service_count" ] && output_result "NACOS_SERVICES_COUNT" "$service_count"
    fi
}

# 检测Nacos实例统计
check_nacos_instances() {
    local instances
    instances=$(nacos_api "v1/ns/instance/list?pageNo=1&pageSize=100&namespaceId=" 2>/dev/null)

    if [ -n "$instances" ]; then
        local instance_count
        instance_count=$(echo "$instances" | grep -o '"count":[0-9]*' | cut -d: -f2 | head -1)
        [ -n "$instance_count" ] && output_result "NACOS_INSTANCES_COUNT" "$instance_count"

        local healthy_count
        healthy_count=$(echo "$instances" | grep -o '"healthyInstanceCount":[0-9]*' | cut -d: -f2 | head -1)
        [ -n "$healthy_count" ] && output_result "NACOS_HEALTHY_INSTANCES" "$healthy_count"

        # 计算健康率
        if [ -n "$instance_count" ] && [ -n "$healthy_count" ] && [ "$instance_count" -gt 0 ]; then
            local health_rate=$((healthy_count * 100 / instance_count))
            output_result "NACOS_HEALTH_RATE" "${health_rate}%"
        fi
    fi
}

# 检测Nacos配置统计
check_nacos_configs() {
    local configs
    configs=$(nacos_api "v1/cs/configs?dataId=&group=&pageNo=1&pageSize=10&tenant=" 2>/dev/null)

    if [ -n "$configs" ]; then
        local config_count
        config_count=$(echo "$configs" | grep -o '"total":[0-9]*' | cut -d: -f2 | head -1)
        [ -n "$config_count" ] && output_result "NACOS_CONFIGS_COUNT" "$config_count"
    fi
}

# 检测Nacos Raft集群状态
check_nacos_raft() {
    local raft_info
    raft_info=$(nacos_api "v1/ns/raft/state" 2>/dev/null)

    if [ -n "$raft_info" ]; then
        if echo "$raft_info" | grep -q "leader"; then
            output_result "NACOS_RAFT_MODE" "是"

            local role
            role=$(echo "$raft_info" | grep -o '"role":"[^"]*"' | cut -d'"' -f4 | head -1)
            [ -n "$role" ] && output_result "NACOS_RAFT_ROLE" "$role"

            local node_count
            node_count=$(echo "$raft_info" | grep -c "peer" || echo "0")
            [ "$node_count" -gt 0 ] && output_result "NACOS_RAFT_NODES" "$node_count"
        else
            output_result "NACOS_RAFT_MODE" "否（单机模式）"
        fi
    fi
}

# 检测Nacos健康状态详情
check_nacos_health_detail() {
    local health_status
    health_status=$(nacos_api "v1/console/health/readiness" 2>/dev/null)

    if [ -z "$health_status" ]; then
        health_status=$(nacos_api "actuator/health" 2>/dev/null)
    fi

    if [ -z "$health_status" ]; then
        health_status=$(nacos_exec curl -s -o /dev/null -w "%{http_code}" "http://localhost:8848/nacos/" 2>/dev/null)
        if [ "$health_status" = "200" ] || [ "$health_status" = "302" ]; then
            health_status="UP"
        fi
    fi

    if [ -n "$health_status" ]; then
        if echo "$health_status" | grep -qi "UP\|200\|302\|healthy"; then
            output_result "NACOS_HEALTH_STATUS" "UP"
            output_result "NACOS_HEALTH_LEVEL" "正常"
        else
            output_result "NACOS_HEALTH_STATUS" "DOWN"
            output_result "NACOS_HEALTH_LEVEL" "严重"
        fi
    else
        output_result "NACOS_HEALTH_STATUS" "DOWN"
        output_result "NACOS_HEALTH_LEVEL" "严重"
    fi
}

# 检测Nacos内存使用详情
check_nacos_memory_detail() {
    local jvm_pid
    jvm_pid=$(nacos_exec jps -l 2>/dev/null | grep nacos | awk '{print $1}')

    if [ -n "$jvm_pid" ]; then
        local heap_info
        heap_info=$(nacos_exec jstat -gc "$jvm_pid" 2>/dev/null | tail -1)

        if [ -n "$heap_info" ]; then
            local heap_used heap_capacity
            heap_used=$(echo "$heap_info" | awk '{print $4}' | tr -d ' ')
            heap_capacity=$(echo "$heap_info" | awk '{print $6}' | tr -d ' ')

            if [ -n "$heap_used" ] && [ -n "$heap_capacity" ] && [ "$heap_capacity" -gt 0 ]; then
                local heap_usage=$((heap_used * 100 / heap_capacity))
                output_result "NACOS_HEAP_USAGE" "${heap_usage}%"
            fi
        fi
    fi
}

# 检测Nacos日志
check_nacos_logs() {
    local log_size
    log_size=$(nacos_exec du -sh /home/nacos/logs 2>/dev/null | awk '{print $1}')

    if [ -n "$log_size" ]; then
        output_result "NACOS_LOG_SIZE" "$log_size"
    fi

    local error_count
    error_count=$(nacos_exec tail -100 /home/nacos/logs/nacos.log 2>/dev/null | grep -c "ERROR" || echo "0")
    output_result "NACOS_RECENT_ERRORS" "$error_count"
}

# 检测Nacos容器资源
check_nacos_resources() {
    local cpu_percent
    cpu_percent=$(docker stats --no-stream --format '{{.CPUPerc}}' "$NACOS_CONTAINER" 2>/dev/null | tr -d '%')
    if [ -n "$cpu_percent" ]; then
        output_result "NACOS_CPU_USAGE" "$cpu_percent"
    fi

    local mem_usage
    mem_usage=$(docker stats --no-stream --format '{{.MemUsage}}' "$NACOS_CONTAINER" 2>/dev/null)
    if [ -n "$mem_usage" ]; then
        output_result "NACOS_MEMORY_USAGE" "$mem_usage"
    fi

    local mem_percent
    mem_percent=$(docker stats --no-stream --format '{{.MemPerc}}' "$NACOS_CONTAINER" 2>/dev/null | tr -d '%')
    if [ -n "$mem_percent" ]; then
        output_result "NACOS_MEMORY_PERCENT" "$mem_percent"
    fi
}

# ==================== 主检测流程 ====================
main() {
    log_info "开始Nacos深度检测..."

    # 检查容器状态（使用模糊匹配）
    local matched_container=""
    matched_container=$(docker ps --format "{{.Names}}" | grep -x "${NACOS_CONTAINER}" | head -1)

    if [ -z "$matched_container" ] && [ -n "$NACOS_CONTAINER" ]; then
        matched_container=$(docker ps --format "{{.Names}}" | grep -i "${NACOS_CONTAINER}" | head -1)
    fi

    if [ -z "$matched_container" ]; then
        log_warn "Nacos容器未运行"
        output_result "NACOS_CONTAINER_STATUS" "未运行"
        return 1
    fi

    eval "NACOS_CONTAINER='${matched_container}'"
    output_result "NACOS_CONTAINER_STATUS" "运行中 (${NACOS_CONTAINER})"

    # 执行各项深度检测
    check_nacos_version 2>/dev/null || true
    check_nacos_services 2>/dev/null || true
    check_nacos_instances 2>/dev/null || true
    check_nacos_configs 2>/dev/null || true
    check_nacos_raft 2>/dev/null || true
    check_nacos_health_detail 2>/dev/null || true
    check_nacos_memory_detail 2>/dev/null || true
    check_nacos_logs 2>/dev/null || true
    check_nacos_resources 2>/dev/null || true

    log_info "Nacos深度检测完成"
}

main
