#!/bin/bash

# systemctl-info - 详细的systemctl信息查看脚本
# 作者: iFlow CLI
# 日期: 2026-02-13
# 版本: 2.0 (模块化版本)

# ═══════════════════════════════════════════════════════════════════════════════
# 颜色定义
# ═══════════════════════════════════════════════════════════════════════════════
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
BRIGHT_RED='\033[1;31m'
BRIGHT_GREEN='\033[1;32m'
BRIGHT_YELLOW='\033[1;33m'
BRIGHT_BLUE='\033[1;34m'
BRIGHT_MAGENTA='\033[1;35m'
BRIGHT_CYAN='\033[1;36m'
BRIGHT_WHITE='\033[1;37m'
ORANGE='\033[38;5;208m'
PINK='\033[38;5;205m'
PURPLE='\033[38;5;141m'
LIME='\033[38;5;154m'
RESET='\033[0m'

# ═══════════════════════════════════════════════════════════════════════════════
# 分割线样式
# ═══════════════════════════════════════════════════════════════════════════════
SEPARATOR="${BRIGHT_CYAN}═══════════════════════════════════════════════════════════════════════════════${RESET}"
THIN_SEPARATOR="${CYAN}──────────────────────────────────────────────────────────────────────────────────────${RESET}"
DASH_SEPARATOR="${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
LINE="${BRIGHT_CYAN}═══════════════════════════════════════════════════════════════════════════════${RESET}"

# ═══════════════════════════════════════════════════════════════════════════════
# 通用工具函数
# ═══════════════════════════════════════════════════════════════════════════════

# 打印标题
print_header() {
    echo -e "${BRIGHT_CYAN}[Systemctl Info Viewer v2.0]${RESET}"
    echo -e "${BRIGHT_CYAN}模块化 Systemd 信息查看脚本${RESET}"
    echo ""
}

# 打印带颜色的小节标题
print_section() {
    echo -e "${THIN_SEPARATOR}"
    echo -e "${BRIGHT_BLUE}[ $1 ]${RESET}"
    echo -e "${THIN_SEPARATOR}"
}

# 打印带图标的信息行
print_info() {
    local icon="$1"
    local label="$2"
    local value="$3"
    local color="$4"
    echo -e "${icon} ${BRIGHT_WHITE}${label}:${RESET} ${color}${value}${RESET}"
}

# 打印子项
print_subitem() {
    local label="$1"
    local value="$2"
    local color="$3"
    echo -e "  ${BRIGHT_CYAN}▸${RESET} ${BRIGHT_WHITE}${label}:${RESET} ${color}${value}${RESET}"
}

# 打印带颜色的列表项
print_list_item() {
    local icon="$1"
    local name="$2"
    local status="$3"
    local status_color="$4"
    local extra="$5"
    printf "${icon} ${BRIGHT_WHITE}%-45s${RESET} ${status_color}%s${RESET}%s\n" "$name" "$status" "$extra"
}

# 获取状态图标和颜色
get_state_icon_color() {
    local state="$1"
    case "$state" in
        active|running|listening)
            echo -e "✅|${BRIGHT_GREEN}"
            ;;
        inactive)
            echo -e "⭕|${BRIGHT_YELLOW}"
            ;;
        failed)
            echo -e "❌|${BRIGHT_RED}"
            ;;
        activating|deactivating)
            echo -e "🔄|${BRIGHT_CYAN}"
            ;;
        *)
            echo -e "❓|${BRIGHT_WHITE}"
            ;;
    esac
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块1: Systemd 版本信息
# ═══════════════════════════════════════════════════════════════════════════════
module_systemd_version() {
    print_section "📋 Systemd 版本信息"
    
    SYSTEMD_VERSION=$(systemctl --version | head -n 1 | awk '{print $2}')
    FEATURE_COUNT=$(systemctl --version | grep -c "features")
    
    print_info "🔧" "Systemd 版本" "$SYSTEMD_VERSION" "${BRIGHT_GREEN}"
    print_info "✨" "支持功能特性" "$FEATURE_COUNT 项" "${LIME}"
    
    echo -e "${BRIGHT_CYAN}详细版本信息:${RESET}"
    systemctl --version | while IFS= read -r line; do
        echo -e "  ${CYAN}${line}${RESET}"
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块2: 系统基础信息
# ═══════════════════════════════════════════════════════════════════════════════
module_system_info() {
    print_section "🖥️ 系统基础信息"
    
    HOSTNAME=$(hostname)
    KERNEL_VERSION=$(uname -r)
    OS_ID=$(grep '^ID=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    OS_NAME=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
    ARCH=$(uname -m)
    UPTIME=$(uptime -p)
    
    print_info "🖥️"  "主机名" "$HOSTNAME" "${BRIGHT_YELLOW}"
    print_info "🐧" "内核版本" "$KERNEL_VERSION" "${ORANGE}"
    print_info "📦" "操作系统ID" "$OS_ID" "${PINK}"
    print_info "💻" "系统名称" "$OS_NAME" "${PURPLE}"
    print_info "🏗️"  "系统架构" "$ARCH" "${BRIGHT_CYAN}"
    print_info "⏱️"  "系统运行时间" "$UPTIME" "${LIME}"
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块3: Systemd 系统状态
# ═══════════════════════════════════════════════════════════════════════════════
module_systemd_status() {
    print_section "⚙️ Systemd 系统状态"
    
    SYSTEM_STATE=$(systemctl is-system-running)
    DEFAULT_TARGET=$(systemctl get-default)
    INIT_PID=$(systemctl show --property=MainPID --value)
    BOOT_TIME=$(systemctl show --property=UserspaceTimestamp --value | cut -d' ' -f1)
    
    case $SYSTEM_STATE in
        running)
            STATE_COLOR="${BRIGHT_GREEN}"
            STATE_ICON="✅"
            ;;
        degraded)
            STATE_COLOR="${BRIGHT_YELLOW}"
            STATE_ICON="⚠️"
            ;;
        maintenance)
            STATE_COLOR="${BRIGHT_RED}"
            STATE_ICON="🔧"
            ;;
        *)
            STATE_COLOR="${BRIGHT_WHITE}"
            STATE_ICON="❓"
            ;;
    esac
    
    print_info "$STATE_ICON" "系统状态" "$SYSTEM_STATE" "$STATE_COLOR"
    print_info "🎯" "默认运行级别" "$DEFAULT_TARGET" "${BRIGHT_CYAN}"
    print_info "🔄" "Init 进程 PID" "$INIT_PID" "${ORANGE}"
    print_info "🚀" "启动时间" "$BOOT_TIME" "${PURPLE}"
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块4: 服务(Service)统计与状态
# ═══════════════════════════════════════════════════════════════════════════════
module_service_stats() {
    print_section "🔌 服务(Service)统计与状态"
    
    TOTAL_UNITS=$(systemctl list-unit-files --type=service --no-legend | wc -l)
    ENABLED_SERVICES=$(systemctl list-unit-files --type=service --state=enabled --no-legend | wc -l)
    DISABLED_SERVICES=$(systemctl list-unit-files --type=service --state=disabled --no-legend | wc -l)
    STATIC_SERVICES=$(systemctl list-unit-files --type=service --state=static --no-legend | wc -l)
    MASKED_SERVICES=$(systemctl list-unit-files --type=service --state=masked --no-legend | wc -l)
    
    RUNNING_SERVICES=$(systemctl list-units --type=service --state=running --no-legend | wc -l)
    FAILED_SERVICES=$(systemctl list-units --type=service --state=failed --no-legend | wc -l)
    
    echo -e "${BRIGHT_CYAN}服务文件统计:${RESET}"
    print_subitem "总服务数" "$TOTAL_UNITS" "${BRIGHT_WHITE}"
    print_subitem "已启用(enabled)" "$ENABLED_SERVICES" "${BRIGHT_GREEN}"
    print_subitem "已禁用(disabled)" "$DISABLED_SERVICES" "${BRIGHT_RED}"
    print_subitem "静态服务(static)" "$STATIC_SERVICES" "${BRIGHT_YELLOW}"
    print_subitem "已屏蔽(masked)" "$MASKED_SERVICES" "${PURPLE}"
    
    echo -e "${BRIGHT_CYAN}服务运行状态:${RESET}"
    print_subitem "运行中" "$RUNNING_SERVICES" "${LIME}"
    print_subitem "失败" "$FAILED_SERVICES" "${BRIGHT_RED}"
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块5: 失败的服务详情
# ═══════════════════════════════════════════════════════════════════════════════
module_failed_services() {
    FAILED_SERVICES=$(systemctl list-units --type=service --state=failed --no-legend | wc -l)
    
    if [ "$FAILED_SERVICES" -gt 0 ]; then
        print_section "❌ 失败的服务详情 (共 $FAILED_SERVICES 个)"
        systemctl list-units --type=service --state=failed --no-pager | sed '1,1d' | while IFS= read -r line; do
            if [ -n "$line" ]; then
                SERVICE_NAME=$(echo "$line" | awk '{print $1}')
                LOAD_STATE=$(echo "$line" | awk '{print $2}')
                ACTIVE_STATE=$(echo "$line" | awk '{print $3}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                DESCRIPTION=$(echo "$line" | awk '{for(i=5;i<=NF;i++)print $i}' | tr '\n' ' ' | sed 's/ $//')
                
                echo -e "${BRIGHT_RED}✗${RESET} ${BRIGHT_WHITE}${SERVICE_NAME}${RESET}"
                echo -e "  ${CYAN}描述:${RESET} ${WHITE}${DESCRIPTION}${RESET}"
                echo -e "  ${CYAN}状态:${RESET} ${RED}${LOAD_STATE}${RESET}|${RED}${ACTIVE_STATE}${RESET}|${RED}${SUB_STATE}${RESET}"
            fi
        done
    else
        print_section "✅ 失败的服务详情"
        echo -e "${BRIGHT_GREEN}  没有失败的服务${RESET}"
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块6: 已屏蔽(Masked)的服务
# ═══════════════════════════════════════════════════════════════════════════════
module_masked_services() {
    MASKED_COUNT=$(systemctl list-unit-files --type=service --state=masked --no-legend | wc -l)
    
    print_section "🚫 已屏蔽(Masked)的服务"
    print_subitem "已屏蔽服务数" "$MASKED_COUNT" "${PURPLE}"
    
    if [ "$MASKED_COUNT" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}已屏蔽的服务列表:${RESET}"
        systemctl list-unit-files --type=service --state=masked --no-legend | while IFS= read -r line; do
            if [ -n "$line" ]; then
                echo -e "  ${PURPLE}✗${RESET} ${BRIGHT_WHITE}${line}${RESET}"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块7: 运行中的服务
# ═══════════════════════════════════════════════════════════════════════════════
module_running_services() {
    print_section "🟢 运行中的服务 (Top 20)"
    
    RUNNING_COUNT=$(systemctl list-units --type=service --state=running --no-legend | wc -l)
    print_subitem "运行中服务总数" "$RUNNING_COUNT" "${LIME}"
    
    echo -e "${BRIGHT_CYAN}运行中的服务列表:${RESET}"
    systemctl list-units --type=service --state=running --no-pager --no-legend | head -20 | while IFS= read -r line; do
        if [ -n "$line" ]; then
            SERVICE_NAME=$(echo "$line" | awk '{print $1}')
            LOAD_STATE=$(echo "$line" | awk '{print $2}')
            ACTIVE_STATE=$(echo "$line" | awk '{print $3}')
            SUB_STATE=$(echo "$line" | awk '{print $4}')
            
            printf "  ${BRIGHT_GREEN}●${RESET} ${BRIGHT_WHITE}%-40s${RESET} ${CYAN}%-8s${RESET} ${BRIGHT_GREEN}%-10s${RESET} ${BRIGHT_CYAN}%s${RESET}\n" "$SERVICE_NAME" "$LOAD_STATE" "$ACTIVE_STATE" "$SUB_STATE"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块8: Timer 定时任务
# ═══════════════════════════════════════════════════════════════════════════════
module_timer() {
    print_section "⏰ Timer 定时任务"
    
    TOTAL_TIMERS=$(systemctl list-units --type=timer --all --no-legend | wc -l)
    ACTIVE_TIMERS=$(systemctl list-units --type=timer --state=active --no-legend | wc -l)
    
    print_subitem "总 Timer 数" "$TOTAL_TIMERS" "${BRIGHT_WHITE}"
    print_subitem "活跃 Timer" "$ACTIVE_TIMERS" "${LIME}"
    
    if [ "$ACTIVE_TIMERS" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}活跃的定时任务 (Top 15):${RESET}"
        systemctl list-units --type=timer --state=active --no-pager --no-legend | head -15 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                TIMER_NAME=$(echo "$line" | awk '{print $1}')
                NEXT_RUN=$(systemctl show "$TIMER_NAME" --property=NextElapseUSec --value 2>/dev/null)
                
                printf "  ${BRIGHT_YELLOW}⏱${RESET} ${BRIGHT_WHITE}%-40s${RESET} ${CYAN}下次执行:${RESET} ${LIME}%s${RESET}\n" "$TIMER_NAME" "$NEXT_RUN"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块9: Socket 单元
# ═══════════════════════════════════════════════════════════════════════════════
module_socket() {
    print_section "🔌 Socket 监听"
    
    TOTAL_SOCKETS=$(systemctl list-units --type=socket --all --no-legend | wc -l)
    LISTENING_SOCKETS=$(systemctl list-units --type=socket --state=listening --no-legend | wc -l)
    
    print_subitem "总 Socket 数" "$TOTAL_SOCKETS" "${BRIGHT_WHITE}"
    print_subitem "监听中" "$LISTENING_SOCKETS" "${LIME}"
    
    if [ "$LISTENING_SOCKETS" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}正在监听的 Socket (Top 15):${RESET}"
        systemctl list-units --type=socket --state=listening --no-pager --no-legend | head -15 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                SOCKET_NAME=$(echo "$line" | awk '{print $1}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                
                printf "  ${BRIGHT_MAGENTA}🔌${RESET} ${BRIGHT_WHITE}%-40s${RESET} ${CYAN}%s${RESET}\n" "$SOCKET_NAME" "$SUB_STATE"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块10: Target 目标单元
# ═══════════════════════════════════════════════════════════════════════════════
module_target() {
    print_section "🎯 Target 目标单元"
    
    ACTIVE_TARGETS=$(systemctl list-units --type=target --state=active --no-legend | wc -l)
    print_subitem "当前激活的 Target" "$ACTIVE_TARGETS" "${LIME}"
    
    echo -e "${BRIGHT_CYAN}重要的 Target 单元:${RESET}"
    IMPORTANT_TARGETS=("default.target" "multi-user.target" "graphical.target" "basic.target" "rescue.target" "emergency.target" "network.target" "sysinit.target")
    
    for target in "${IMPORTANT_TARGETS[@]}"; do
        TARGET_STATE=$(systemctl is-active "$target" 2>/dev/null)
        TARGET_ENABLED=$(systemctl is-enabled "$target" 2>/dev/null)
        
        if [ -n "$TARGET_STATE" ]; then
            case $TARGET_STATE in
                active) STATE_ICON="✅"; STATE_COLOR="${BRIGHT_GREEN}" ;;
                inactive) STATE_ICON="⭕"; STATE_COLOR="${BRIGHT_YELLOW}" ;;
                *) STATE_ICON="❓"; STATE_COLOR="${BRIGHT_WHITE}" ;;
            esac
            
            printf "  ${STATE_ICON} ${BRIGHT_WHITE}%-25s${RESET} ${STATE_COLOR}状态:%-10s${RESET} ${CYAN}启用:%s${RESET}\n" "$target" "$TARGET_STATE" "$TARGET_ENABLED"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块11: Mount 和 Automount 单元
# ═══════════════════════════════════════════════════════════════════════════════
module_mount() {
    print_section "📁 挂载点(Mount)信息"
    
    TOTAL_MOUNTS=$(systemctl list-units --type=mount --all --no-legend | wc -l)
    ACTIVE_MOUNTS=$(systemctl list-units --type=mount --state=active --no-legend | wc -l)
    TOTAL_AUTOMOUNTS=$(systemctl list-units --type=automount --all --no-legend | wc -l)
    ACTIVE_AUTOMOUNTS=$(systemctl list-units --type=automount --state=active --no-legend | wc -l)
    
    print_subitem "挂载点总数" "$TOTAL_MOUNTS" "${BRIGHT_WHITE}"
    print_subitem "活跃挂载点" "$ACTIVE_MOUNTS" "${LIME}"
    print_subitem "自动挂载总数" "$TOTAL_AUTOMOUNTS" "${BRIGHT_WHITE}"
    print_subitem "活跃自动挂载" "$ACTIVE_AUTOMOUNTS" "${LIME}"
    
    if [ "$ACTIVE_MOUNTS" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}挂载点详情 (Top 10):${RESET}"
        systemctl list-units --type=mount --state=active --no-pager --no-legend | head -10 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                MOUNT_NAME=$(echo "$line" | awk '{print $1}')
                MOUNT_POINT=$(systemctl show "$MOUNT_NAME" --property=Where --value 2>/dev/null)
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                
                printf "  ${BRIGHT_CYAN}📂${RESET} ${BRIGHT_WHITE}%-35s${RESET} ${PURPLE}%s${RESET}\n" "$MOUNT_POINT" "$SUB_STATE"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块12: Path 单元
# ═══════════════════════════════════════════════════════════════════════════════
module_path() {
    print_section "📍 Path 路径监控单元"
    
    TOTAL_PATHS=$(systemctl list-units --type=path --all --no-legend | wc -l)
    ACTIVE_PATHS=$(systemctl list-units --type=path --state=active --no-legend | wc -l)
    
    print_subitem "总 Path 数" "$TOTAL_PATHS" "${BRIGHT_WHITE}"
    print_subitem "活跃 Path" "$ACTIVE_PATHS" "${LIME}"
    
    if [ "$ACTIVE_PATHS" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}活跃的 Path 监控 (Top 10):${RESET}"
        systemctl list-units --type=path --state=active --no-pager --no-legend | head -10 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                PATH_NAME=$(echo "$line" | awk '{print $1}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                PATH_PATH=$(systemctl show "$PATH_NAME" --property=PathExists --value 2>/dev/null)
                
                printf "  ${BRIGHT_CYAN}📍${RESET} ${BRIGHT_WHITE}%-40s${RESET} ${CYAN}监控:${RESET} ${LIME}%s${RESET} ${CYAN}状态:%s${RESET}\n" "$PATH_NAME" "$PATH_PATH" "$SUB_STATE"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块13: Device 单元
# ═══════════════════════════════════════════════════════════════════════════════
module_device() {
    print_section "🔧 Device 设备单元"
    
    TOTAL_DEVICES=$(systemctl list-units --type=device --all --no-legend | wc -l)
    ACTIVE_DEVICES=$(systemctl list-units --type=device --state=active --no-legend | wc -l)
    
    print_subitem "总设备数" "$TOTAL_DEVICES" "${BRIGHT_WHITE}"
    print_subitem "活跃设备" "$ACTIVE_DEVICES" "${LIME}"
    
    if [ "$ACTIVE_DEVICES" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}活跃的设备 (Top 10):${RESET}"
        systemctl list-units --type=device --state=active --no-pager --no-legend | head -10 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                DEVICE_NAME=$(echo "$line" | awk '{print $1}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                
                printf "  ${BRIGHT_YELLOW}🔧${RESET} ${BRIGHT_WHITE}%-45s${RESET} ${LIME}%s${RESET}\n" "$DEVICE_NAME" "$SUB_STATE"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块14: Scope 和 Slice 单元
# ═══════════════════════════════════════════════════════════════════════════════
module_scope_slice() {
    print_section "📊 Scope 和 Slice 资源控制单元"
    
    # Scope 单元
    TOTAL_SCOPES=$(systemctl list-units --type=scope --all --no-legend | wc -l)
    ACTIVE_SCOPES=$(systemctl list-units --type=scope --state=running --no-legend | wc -l)
    
    print_subitem "Scope 总数" "$TOTAL_SCOPES" "${BRIGHT_WHITE}"
    print_subitem "运行中 Scope" "$ACTIVE_SCOPES" "${LIME}"
    
    if [ "$ACTIVE_SCOPES" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}运行中的 Scope (Top 10):${RESET}"
        systemctl list-units --type=scope --state=running --no-pager --no-legend | head -10 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                SCOPE_NAME=$(echo "$line" | awk '{print $1}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                
                printf "  ${BRIGHT_CYAN}📊${RESET} ${BRIGHT_WHITE}%-45s${RESET} ${LIME}%s${RESET}\n" "$SCOPE_NAME" "$SUB_STATE"
            fi
        done
    fi
    
    # Slice 单元
    echo ""
    TOTAL_SLICES=$(systemctl list-units --type=slice --all --no-legend | wc -l)
    ACTIVE_SLICES=$(systemctl list-units --type=slice --state=active --no-legend | wc -l)
    
    print_subitem "Slice 总数" "$TOTAL_SLICES" "${BRIGHT_WHITE}"
    print_subitem "活跃 Slice" "$ACTIVE_SLICES" "${LIME}"
    
    if [ "$ACTIVE_SLICES" -gt 0 ]; then
        echo -e "${BRIGHT_CYAN}活跃的 Slice:${RESET}"
        systemctl list-units --type=slice --state=active --no-pager --no-legend | head -10 | while IFS= read -r line; do
            if [ -n "$line" ]; then
                SLICE_NAME=$(echo "$line" | awk '{print $1}')
                SUB_STATE=$(echo "$line" | awk '{print $4}')
                MEMORY=$(systemctl show "$SLICE_NAME" --property=MemoryCurrent --value 2>/dev/null)
                if [ -n "$MEMORY" ] && [ "$MEMORY" != "[not set]" ]; then
                    MEMORY_DISPLAY="内存: $(numfmt --to=iec $MEMORY 2>/dev/null || echo $MEMORY)"
                else
                    MEMORY_DISPLAY=""
                fi
                
                printf "  ${BRIGHT_MAGENTA}📦${RESET} ${BRIGHT_WHITE}%-30s${RESET} ${LIME}%s${RESET} %s\n" "$SLICE_NAME" "$SUB_STATE" "$MEMORY_DISPLAY"
            fi
        done
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块15: 依赖关系
# ═══════════════════════════════════════════════════════════════════════════════
module_dependencies() {
    print_section "🔗 系统依赖关系"
    
    # 显示默认.target的依赖树
    DEFAULT_TARGET=$(systemctl get-default)
    
    echo -e "${BRIGHT_CYAN}默认目标 '$DEFAULT_TARGET' 的依赖 (前15个):${RESET}"
    systemctl list-dependencies "$DEFAULT_TARGET" --no-pager --no-legend | head -15 | while IFS= read -r line; do
        if [ -n "$line" ]; then
            UNIT_TYPE=$(echo "$line" | grep -o '\.[a-z]*$' | tr -d '.')
            case "$UNIT_TYPE" in
                service) ICON="🔌" ;;
                target) ICON="🎯" ;;
                timer) ICON="⏰" ;;
                socket) ICON="🔌" ;;
                mount) ICON="📁" ;;
                path) ICON="📍" ;;
                *) ICON="📄" ;;
            esac
            printf "  ${ICON} ${BRIGHT_WHITE}%s${RESET}\n" "$line"
        fi
    done
    
    # 显示被依赖最多的服务
    echo ""
    echo -e "${BRIGHT_CYAN}系统关键.target的依赖数量:${RESET}"
    for target in "multi-user.target" "graphical.target" "basic.target" "network.target"; do
        DEP_COUNT=$(systemctl list-dependencies "$target" --no-legend 2>/dev/null | wc -l)
        if [ -n "$DEP_COUNT" ]; then
            print_subitem "$target" "$DEP_COUNT 个依赖" "${BRIGHT_CYAN}"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块16: Systemd 日志信息
# ═══════════════════════════════════════════════════════════════════════════════
module_journal() {
    print_section "📝 Systemd Journal 日志摘要"
    
    JOURNAL_SIZE=$(journalctl --disk-usage | grep "Journals use" | awk '{print $3,$4}')
    JOURNAL_ENTRIES=$(journalctl --no-pager -n 0 2>/dev/null | wc -l)
    
    print_subitem "日志磁盘占用" "$JOURNAL_SIZE" "${ORANGE}"
    print_subitem "日志总条目" "$JOURNAL_ENTRIES" "${BRIGHT_CYAN}"
    
    echo -e "${BRIGHT_CYAN}最近的错误日志 (最近5条):${RESET}"
    journalctl -p err -n 5 --no-pager 2>/dev/null | while IFS= read -r line; do
        if [ -n "$line" ]; then
            echo -e "  ${RED}✗${RESET} ${WHITE}${line}${RESET}"
        fi
    done
    
    echo -e "${BRIGHT_CYAN}最近的警告日志 (最近3条):${RESET}"
    journalctl -p warning -n 3 --no-pager 2>/dev/null | while IFS= read -r line; do
        if [ -n "$line" ]; then
            echo -e "  ${YELLOW}⚠${RESET} ${WHITE}${line}${RESET}"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块17: Systemd 环境变量
# ═══════════════════════════════════════════════════════════════════════════════
module_environment() {
    print_section "🔧 Systemd 环境变量"
    
    ENV_COUNT=$(systemctl show-environment 2>/dev/null | wc -l)
    print_subitem "环境变量数量" "$ENV_COUNT" "${BRIGHT_CYAN}"
    
    echo -e "${BRIGHT_CYAN}系统环境变量:${RESET}"
    systemctl show-environment 2>/dev/null | head -15 | while IFS= read -r line; do
        if [ -n "$line" ]; then
            KEY=$(echo "$line" | cut -d'=' -f1)
            VALUE=$(echo "$line" | cut -d'=' -f2-)
            echo -e "  ${BRIGHT_YELLOW}●${RESET} ${BRIGHT_CYAN}${KEY}${RESET}=${BRIGHT_WHITE}${VALUE}${RESET}"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块18: Cgroup 信息
# ═══════════════════════════════════════════════════════════════════════════════
module_cgroup() {
    print_section "🧊 Cgroup 信息"
    
    # 获取 cgroup 版本
    if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
        CGROUP_VERSION="v2 (unified)"
    else
        CGROUP_VERSION="v1 (legacy)"
    fi
    
    print_subitem "Cgroup 版本" "$CGROUP_VERSION" "${BRIGHT_CYAN}"
    
    # 获取控制器信息
    if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
        CONTROLLERS=$(cat /sys/fs/cgroup/cgroup.controllers 2>/dev/null | tr ' ' ', ')
    else
        CONTROLLERS=$(cat /sys/fs/cgroup/devices.list 2>/dev/null | head -1 | cut -d' ' -f1 || echo "N/A")
    fi
    print_subitem "可用控制器" "$CONTROLLERS" "${LIME}"
    
    # Slice 资源统计
    echo -e "${BRIGHT_CYAN}Slice 资源使用 (Top 5):${RESET}"
    for slice in $(systemctl list-units --type=slice --state=active --no-legend | awk '{print $1}' | head -5); do
        MEM_CURRENT=$(systemctl show "$slice" --property=MemoryCurrent --value 2>/dev/null)
        MEM_MAX=$(systemctl show "$slice" --property=MemoryMax --value 2>/dev/null)
        CPU_WEIGHT=$(systemctl show "$slice" --property=CPUWeight --value 2>/dev/null)
        
        MEM_DISP=""
        if [ -n "$MEM_CURRENT" ] && [ "$MEM_CURRENT" != "[not set]" ]; then
            MEM_DISP="内存: $(numfmt --to=iec $MEM_CURRENT 2>/dev/null || echo $MEM_CURRENT)"
        fi
        if [ -n "$CPU_WEIGHT" ] && [ "$CPU_WEIGHT" != "[not set]" ]; then
            MEM_DISP="$MEM_DISP CPU权重: $CPU_WEIGHT"
        fi
        
        if [ -n "$MEM_DISP" ]; then
            printf "  ${BRIGHT_MAGENTA}📦${RESET} ${BRIGHT_WHITE}%-25s${RESET} ${LIME}%s${RESET}\n" "$slice" "$MEM_DISP"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块19: 系统性能信息
# ═══════════════════════════════════════════════════════════════════════════════
module_performance() {
    print_section "📊 系统性能信息"
    
    # 获取 CPU 使用率
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
    
    # 获取内存信息
    MEM_INFO=$(free -h | grep "Mem:")
    MEM_TOTAL=$(echo "$MEM_INFO" | awk '{print $2}')
    MEM_USED=$(echo "$MEM_INFO" | awk '{print $3}')
    MEM_FREE=$(echo "$MEM_INFO" | awk '{print $4}')
    MEM_PERCENT=$(free | grep "Mem:" | awk '{printf "%.1f", $3/$2*100}')
    
    # 获取启动时间
    BOOT_TIME_SEC=$(systemctl show --property=UserspaceTimestampMonotonic --value | cut -d' ' -f1)
    BOOT_TIME_SEC=${BOOT_TIME_SEC:-0}
    BOOT_TIME_SEC=$((BOOT_TIME_SEC / 1000000))
    
    print_subitem "CPU 使用率" "${CPU_USAGE}%" "${BRIGHT_YELLOW}"
    print_subitem "内存总量" "$MEM_TOTAL" "${BRIGHT_CYAN}"
    print_subitem "已用内存" "$MEM_USED (${MEM_PERCENT}%)" "${ORANGE}"
    print_subitem "可用内存" "$MEM_FREE" "${LIME}"
    print_subitem "启动耗时" "${BOOT_TIME_SEC} 秒" "${PURPLE}"
    
    # Swap 信息
    SWAP_TOTAL=$(free -h | grep "Swap:" | awk '{print $2}')
    SWAP_USED=$(free -h | grep "Swap:" | awk '{print $3}')
    SWAP_FREE=$(free -h | grep "Swap:" | awk '{print $4}')
    
    if [ "$SWAP_TOTAL" != "0" ]; then
        print_subitem "Swap总量" "$SWAP_TOTAL" "${PINK}"
        print_subitem "Swap已用" "$SWAP_USED" "${PINK}"
        print_subitem "Swap可用" "$SWAP_FREE" "${PINK}"
    fi
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块20: 电源管理状态
# ═══════════════════════════════════════════════════════════════════════════════
module_power_management() {
    print_section "🔋 电源管理状态"
    
    # 检查 systemd-suspend 服务
    if systemctl list-unit-files | grep -q "systemd-suspend.service"; then
        SUSPEND_STATE=$(systemctl is-enabled systemd-suspend.service 2>/dev/null || echo "N/A")
        print_subitem "Suspend 服务" "$SUSPEND_STATE" "${BRIGHT_CYAN}"
    fi
    
    # 检查 systemd-hibernate 服务
    if systemctl list-unit-files | grep -q "systemd-hibernate.service"; then
        HIBERNATE_STATE=$(systemctl is-enabled systemd-hibernate.service 2>/dev/null || echo "N/A")
        print_subitem "Hibernate 服务" "$HIBERNATE_STATE" "${BRIGHT_CYAN}"
    fi
    
    # 检查 logind 状态
    if systemctl list-unit-files | grep -q "systemd-logind.service"; then
        LOGIND_STATE=$(systemctl is-active systemd-logind.service 2>/dev/null || echo "N/A")
        print_subitem "Logind 状态" "$LOGIND_STATE" "${LIME}"
    fi
    
    # 显示电源相关事件
    echo -e "${BRIGHT_CYAN}最近的电源相关日志:${RESET}"
    journalctl -u systemd-logind -u upower -n 3 --no-pager 2>/dev/null | while IFS= read -r line; do
        if [ -n "$line" ]; then
            echo -e "  ${CYAN}▸${RESET} ${WHITE}${line}${RESET}"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块21: 关键服务状态
# ═══════════════════════════════════════════════════════════════════════════════
module_critical_services() {
    print_section "🔑 关键系统服务状态"
    
    KEY_SERVICES=(
        "sshd.service"
        "NetworkManager.service"
        "cron.service"
        "rsyslog.service"
        "dbus.service"
        "systemd-logind.service"
        "systemd-journald.service"
        "systemd-udevd.service"
        "polkit.service"
    )
    
    for service in "${KEY_SERVICES[@]}"; do
        if systemctl list-unit-files 2>/dev/null | grep -q "$service"; then
            SERVICE_STATE=$(systemctl is-active "$service" 2>/dev/null)
            SERVICE_ENABLED=$(systemctl is-enabled "$service" 2>/dev/null)
            
            case $SERVICE_STATE in
                active) STATE_ICON="✅"; STATE_COLOR="${BRIGHT_GREEN}" ;;
                inactive) STATE_ICON="⭕"; STATE_COLOR="${BRIGHT_YELLOW}" ;;
                failed) STATE_ICON="❌"; STATE_COLOR="${BRIGHT_RED}" ;;
                *) STATE_ICON="❓"; STATE_COLOR="${BRIGHT_WHITE}" ;;
            esac
            
            printf "  ${STATE_ICON} ${BRIGHT_WHITE}%-30s${RESET} ${STATE_COLOR}%-10s${RESET} ${CYAN}启用:%s${RESET}\n" "$service" "$SERVICE_STATE" "$SERVICE_ENABLED"
        fi
    done
}

# ═══════════════════════════════════════════════════════════════════════════════
# 模块22: 常用命令提示
# ═══════════════════════════════════════════════════════════════════════════════
module_help() {
    print_section "💡 常用 Systemctl 命令"
    
    echo -e "${BRIGHT_YELLOW}=== 服务管理 ===${RESET}"
    echo -e "${BRIGHT_WHITE}systemctl status <service>${RESET}     - 查看服务状态"
    echo -e "${BRIGHT_WHITE}systemctl start <service>${RESET}      - 启动服务"
    echo -e "${BRIGHT_WHITE}systemctl stop <service>${RESET}       - 停止服务"
    echo -e "${BRIGHT_WHITE}systemctl restart <service>${RESET}     - 重启服务"
    echo -e "${BRIGHT_WHITE}systemctl enable <service>${RESET}      - 启用开机自启"
    echo -e "${BRIGHT_WHITE}systemctl disable <service>${RESET}     - 禁用开机自启"
    echo -e "${BRIGHT_WHITE}systemctl mask <service>${RESET}       - 屏蔽服务"
    echo -e "${BRIGHT_WHITE}systemctl unmask <service>${RESET}     - 取消屏蔽"
    
    echo -e "${BRIGHT_YELLOW}=== 状态查看 ===${RESET}"
    echo -e "${BRIGHT_WHITE}systemctl is-active <service>${RESET}  - 检查服务是否活跃"
    echo -e "${BRIGHT_WHITE}systemctl is-enabled <service>${RESET} - 检查服务是否启用"
    echo -e "${BRIGHT_WHITE}systemctl --failed${RESET}             - 查看失败的服务"
    echo -e "${BRIGHT_WHITE}systemctl list-dependencies <unit>${RESET} - 查看依赖"
    
    echo -e "${BRIGHT_YELLOW}=== 日志查看 ===${RESET}"
    echo -e "${BRIGHT_WHITE}journalctl -u <service>${RESET}         - 查看服务日志"
    echo -e "${BRIGHT_WHITE}journalctl -xe${RESET}                  - 查看最近日志"
    echo -e "${BRIGHT_WHITE}journalctl -p err${RESET}                - 查看错误日志"
    
    echo -e "${BRIGHT_YELLOW}=== 电源管理 ===${RESET}"
    echo -e "${BRIGHT_WHITE}systemctl suspend${RESET}                - 挂起"
    echo -e "${BRIGHT_WHITE}systemctl hibernate${RESET}             - 休眠"
    echo -e "${BRIGHT_WHITE}systemctl reboot${RESET}                - 重启"
    echo -e "${BRIGHT_WHITE}systemctl poweroff${RESET}              - 关机"
}

# ═══════════════════════════════════════════════════════════════════════════════
# 主函数 - 模块调度
# ═══════════════════════════════════════════════════════════════════════════════
main() {
    print_header
    
    # 基础信息模块
    module_systemd_version
    module_system_info
    module_systemd_status
    
    # 单元统计模块
    module_service_stats
    module_running_services
    module_failed_services
    module_masked_services
    
    # 各类单元模块
    module_timer
    module_socket
    module_target
    module_mount
    module_path
    module_device
    module_scope_slice
    
    # 系统信息模块
    module_dependencies
    module_journal
    module_environment
    module_cgroup
    module_performance
    module_power_management
    
    # 服务状态模块
    module_critical_services
    
    # 帮助信息
    module_help
    
    # 结束
    echo -e "${DASH_SEPARATOR}"
    echo -e "${BRIGHT_MAGENTA}✨ 信息收集完成！时间: $(date '+%Y-%m-%d %H:%M:%S') ✨${RESET}"
    echo -e "${DASH_SEPARATOR}"
}

# 执行主函数
main "@"