#!/bin/bash
################################################################################
# Python应用检测模块
# 功能: 检测Python容器状态、进程、资源使用等
# 作者: 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
fi

# Python容器名称
PYTHON_CONTAINER="${CONTAINERS[python]}"

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

python_exec() {
    docker exec "$PYTHON_CONTAINER" $@ 2>/dev/null
}

# ==================== 检测函数 ====================

# 检测Python容器状态
check_python_container() {
    local matched_container=""
    if command -v docker &> /dev/null; then
        # 尝试精确匹配
        matched_container=$(docker ps --format "{{.Names}}" | grep -x "${PYTHON_CONTAINER}" | head -1)

        # 如果精确匹配失败，尝试模糊匹配
        if [ -z "$matched_container" ] && [ -n "$PYTHON_CONTAINER" ]; then
            matched_container=$(docker ps --format "{{.Names}}" | grep -i "${PYTHON_CONTAINER}" | head -1)
        fi
    fi

    if [ -n "$matched_container" ]; then
        eval "PYTHON_CONTAINER='${matched_container}'"
        output_result "PYTHON_CONTAINER_STATUS" "运行中 (${PYTHON_CONTAINER})"
        output_result "PYTHON_CONTAINER_LEVEL" "正常"
        return 0
    else
        # 检查容器是否存在但未运行
        matched_container=$(docker ps -a --format "{{.Names}}" | grep -i "${PYTHON_CONTAINER}" | head -1)
        if [ -n "$matched_container" ]; then
            output_result "PYTHON_CONTAINER_STATUS" "已停止 (${matched_container})"
            output_result "PYTHON_CONTAINER_LEVEL" "警告"
        else
            output_result "PYTHON_CONTAINER_STATUS" "未运行"
            output_result "PYTHON_CONTAINER_LEVEL" "严重"
        fi
        return 1
    fi
}

# 检测Python版本
check_python_version() {
    local py_version
    py_version=$(python_exec python --version 2>&1 | awk '{print $2}')
    [ -n "$py_version" ] && output_result "PYTHON_VERSION" "$py_version"
}

# 检测Python进程数
check_python_processes() {
    local py_count
    py_count=$(python_exec ps aux 2>/dev/null | grep -c "python" || echo "0")
    output_result "PYTHON_PROCESSES" "$py_count"
}

# 检测容器内进程列表
check_python_process_list() {
    local process_list
    process_list=$(python_exec ps aux 2>/dev/null | grep -v "PID" | grep -v "ps aux" | awk '{print $1, $2, $3, $4, $11}' | head -20)

    if [ -n "$process_list" ]; then
        # 统计进程数
        local total_processes
        total_processes=$(echo "$process_list" | wc -l)
        output_result "PYTHON_PROCESS_COUNT" "$total_processes"

        # 格式化进程列表（USER PID CPU% MEM% COMMAND）
        local formatted
        formatted=$(echo "$process_list" | tr '\n' '|' | sed 's/|$//')
        output_result "PYTHON_PROCESS_LIST" "$formatted"

        # 获取Python进程详情
        local py_processes
        py_processes=$(echo "$process_list" | grep -i "python" | head -10)
        if [ -n "$py_processes" ]; then
            output_result "PYTHON_PROCESSES_DETAIL" "$(echo "$py_processes" | tr '\n' '|' | sed 's/|$//')"
        fi
    fi
}

# 检测Python容器资源使用
check_python_resources() {
    # 内存使用
    local py_mem
    py_mem=$(docker stats --no-stream --format "{{.MemUsage}}" "$PYTHON_CONTAINER" 2>/dev/null | head -1)
    [ -n "$py_mem" ] && output_result "PYTHON_MEMORY" "$py_mem"

    # CPU使用率
    local py_cpu
    py_cpu=$(docker stats --no-stream --format "{{.CPUPerc}}" "$PYTHON_CONTAINER" 2>/dev/null | head -1)
    [ -n "$py_cpu" ] && output_result "PYTHON_CPU" "$py_cpu"
}

# 检测Python应用日志
check_python_logs() {
    local log_errors=0
    log_errors=$(docker logs --tail 500 "$PYTHON_CONTAINER" 2>&1 | grep -ciE "ERROR|Exception|Traceback" || echo "0")
    log_errors=$(echo "$log_errors" | tail -1)

    output_result "PYTHON_LOG_ERRORS" "$log_errors"

    if [ "$log_errors" -gt 20 ]; then
        output_result "PYTHON_LOG_LEVEL" "警告"
    else
        output_result "PYTHON_LOG_LEVEL" "正常"
    fi
}

# ==================== 主检测流程 ====================
main() {
    log_info "开始Python应用检测..."

    if ! check_python_container; then
        log_warn "Python容器未运行，跳过其他检测"
        return
    fi

    check_python_version
    check_python_processes
    check_python_resources
    check_python_logs
    check_python_process_list

    log_info "Python应用检测完成"
}

main
