#!/bin/bash

#############################################################################
# Platform Health Check Module
# Verifies all detected platform components are running and healthy
# Works across all supported control panels and operating systems
#############################################################################

set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
LIB_DIR="$BASE_DIR/lib"

# Load libraries
source "$LIB_DIR/common-functions.sh"
source "$LIB_DIR/system-detect.sh"

# Ensure system detection is complete
[ -z "${SYS_DETECTION_COMPLETE:-}" ] && initialize_system_detection

#############################################################################
# COLORS & FORMATTING
#############################################################################

PASS="${GREEN}✓${NC}"
FAIL="${RED}✗${NC}"
WARN="${YELLOW}⚠${NC}"
INFO="${CYAN}ℹ${NC}"

#############################################################################
# SERVICE STATUS FUNCTIONS
#############################################################################

check_service_running() {
    local service_name="$1"
    local systemctl_name="${2:-$service_name}"

    if systemctl is-active --quiet "$systemctl_name" 2>/dev/null; then
        echo "$PASS ${GREEN}${service_name}${NC} is running"
        return 0
    else
        echo "$FAIL ${RED}${service_name}${NC} is NOT running"
        return 1
    fi
}

check_process_running() {
    local process_name="$1"
    local display_name="${2:-$process_name}"

    if pgrep -x "$process_name" > /dev/null 2>&1; then
        echo "$PASS ${GREEN}${display_name}${NC} process is running"
        return 0
    else
        echo "$FAIL ${RED}${display_name}${NC} process is NOT running"
        return 1
    fi
}

check_port_listening() {
    local port="$1"
    local service="$2"

    if netstat -tlnp 2>/dev/null | grep -q ":$port "; then
        echo "$PASS Port ${GREEN}$port${NC} (${service}) is listening"
        return 0
    else
        echo "$FAIL Port ${RED}$port${NC} (${service}) is NOT listening"
        return 1
    fi
}

#############################################################################
# PLATFORM-SPECIFIC HEALTH CHECKS
#############################################################################

check_cpanel_health() {
    echo ""
    print_section "cPanel Health"
    echo ""

    # Check cPanel services
    check_process_running "cpanel" "cPanel daemon" || true
    check_service_running "cpsrvd" "cPanel service" || true

    # Check Apache
    if [ "$SYS_WEB_SERVER" = "apache" ]; then
        check_service_running "httpd" "Apache httpd" || check_service_running "apache2" "Apache" || true
    fi

    # Check MySQL/MariaDB
    if [ "$SYS_DB_TYPE" != "none" ]; then
        check_service_running "mysql" "MySQL/MariaDB" || check_service_running "mariadb" || true
    fi

    # Check DNS (BIND)
    check_service_running "named" "BIND DNS" 2>/dev/null || echo "$INFO DNS not checked (may not be running locally)" || true

    echo ""
}

check_plesk_health() {
    echo ""
    print_section "Plesk Health"
    echo ""

    # Check Plesk core services
    check_process_running "sw-engine" "Plesk backend" || true
    check_process_running "sw-cp-server" "Plesk control panel" || true

    # Check web server
    if [ "$SYS_WEB_SERVER" = "apache" ]; then
        check_service_running "apache2" "Apache" || check_service_running "httpd" || true
    elif [ "$SYS_WEB_SERVER" = "nginx" ]; then
        check_service_running "nginx" "Nginx" || true
    fi

    # Check database
    if [ "$SYS_DB_TYPE" != "none" ]; then
        check_service_running "mysql" "MySQL" || check_service_running "mariadb" || true
    fi

    echo ""
}

check_interworx_health() {
    echo ""
    print_section "InterWorx Health"
    echo ""

    # Check InterWorx services
    check_process_running "iworx" "InterWorx daemon" || true
    check_process_running "iworx-httpd" "InterWorx HTTP daemon" || true

    # Check NodeWorx API
    if [ -x "/usr/bin/nodeworx" ]; then
        echo "$PASS NodeWorx CLI is available"
    fi

    # Check web server
    check_service_running "httpd" "Apache httpd" || true

    # Check database
    if [ "$SYS_DB_TYPE" != "none" ]; then
        check_service_running "mysql" "MySQL" || check_service_running "mariadb" || true
    fi

    echo ""
}

check_standalone_health() {
    echo ""
    print_section "Standalone Server Health"
    echo ""

    # Check web server
    if [ "$SYS_WEB_SERVER" = "apache" ]; then
        check_service_running "httpd" "Apache httpd" || check_service_running "apache2" || true
    elif [ "$SYS_WEB_SERVER" = "nginx" ]; then
        check_service_running "nginx" "Nginx" || true
    fi

    # Check database
    if [ "$SYS_DB_TYPE" != "none" ]; then
        check_service_running "mysql" "MySQL" || check_service_running "mariadb" || true
    fi

    echo ""
}

#############################################################################
# FIREWALL HEALTH CHECKS
#############################################################################

check_firewall_health() {
    echo ""
    print_section "Firewall Status"
    echo ""

    case "$SYS_FIREWALL" in
        csf)
            check_process_running "lfd" "LFD (CSF)" || true
            if [ -f "/etc/csf/csf.conf" ]; then
                if grep -q "^TESTING = \"0\"" /etc/csf/csf.conf 2>/dev/null; then
                    echo "$PASS CSF is in ${GREEN}production mode${NC}"
                else
                    echo "$WARN CSF is in ${YELLOW}testing mode${NC}"
                fi
            fi
            ;;
        firewalld)
            check_service_running "firewalld" "firewalld" || true
            ;;
        ufw)
            if ufw status 2>/dev/null | grep -q "Status: active"; then
                echo "$PASS UFW is ${GREEN}active${NC}"
            else
                echo "$WARN UFW is ${YELLOW}inactive${NC}"
            fi
            ;;
        iptables)
            local rule_count=$(iptables -L -n 2>/dev/null | grep -c "^Chain" || echo 0)
            if [ "$rule_count" -gt 0 ]; then
                echo "$PASS iptables has ${rule_count} chains configured"
            else
                echo "$WARN No iptables rules found"
            fi
            ;;
        *)
            echo "$INFO No firewall detected"
            ;;
    esac

    echo ""
}

#############################################################################
# PHP HEALTH CHECKS
#############################################################################

check_php_health() {
    echo ""
    print_section "PHP Status"
    echo ""

    if [ ${#SYS_PHP_VERSIONS[@]} -eq 0 ]; then
        echo "$WARN No PHP versions detected"
        return
    fi

    for version in "${SYS_PHP_VERSIONS[@]}"; do
        php_binary=$(command -v "php${version}" 2>/dev/null || command -v php 2>/dev/null || echo "")
        if [ -x "$php_binary" ]; then
            echo "$PASS PHP $version is available"
        else
            echo "$FAIL PHP $version binary not found"
        fi
    done

    # Check PHP-FPM if installed
    if command_exists php-fpm; then
        if check_process_running "php-fpm" "PHP-FPM" 2>/dev/null; then
            echo ""
        else
            echo "$WARN PHP-FPM is installed but not running"
        fi
    fi

    echo ""
}

#############################################################################
# STORAGE & RESOURCE CHECKS
#############################################################################

check_storage() {
    echo ""
    print_section "Storage & Resources"
    echo ""

    # Disk usage
    local root_usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
    if [ "$root_usage" -gt 90 ]; then
        echo "$FAIL Disk usage is ${RED}${root_usage}%${NC} (CRITICAL)"
    elif [ "$root_usage" -gt 80 ]; then
        echo "$WARN Disk usage is ${YELLOW}${root_usage}%${NC} (Warning)"
    else
        echo "$PASS Disk usage is ${GREEN}${root_usage}%${NC}"
    fi

    # Memory check
    local mem_available=$(free -h | awk '/^Mem:/ {print $7}')
    echo "$INFO Available Memory: $mem_available"

    # Swap check
    local swap_total=$(free -h | awk '/^Swap:/ {print $2}')
    if [ "$swap_total" = "0B" ]; then
        echo "$WARN No swap space configured"
    else
        local swap_used=$(free -h | awk '/^Swap:/ {print $3}')
        echo "$INFO Swap: $swap_used / $swap_total"
    fi

    echo ""
}

#############################################################################
# CLOUDFLARE STATUS
#############################################################################

check_cloudflare_status() {
    if [ "$SYS_CLOUDFLARE_ACTIVE" = "yes" ]; then
        echo ""
        print_section "CloudFlare"
        echo ""
        echo "$PASS CloudFlare integration is ${GREEN}active${NC}"
        echo ""
    fi
}

#############################################################################
# GENERAL SYSTEM CHECKS
#############################################################################

check_system_critical() {
    echo ""
    print_section "Critical System Checks"
    echo ""

    # Check if running as root
    if [ "$EUID" -eq 0 ]; then
        echo "$PASS Running as ${GREEN}root${NC}"
    else
        echo "$FAIL Not running as root - some checks may fail"
    fi

    # Check system date/time
    if command_exists ntpstat; then
        echo "$PASS NTP is available for time synchronization"
    else
        echo "$INFO NTP tools not installed (may still be synchronized)"
    fi

    # Check SSH
    check_service_running "sshd" "SSH" || true

    # Check mail service
    if check_process_running "exim" "Exim" 2>/dev/null || check_process_running "postfix" "Postfix" 2>/dev/null; then
        true
    else
        echo "$INFO Mail service not detected"
    fi

    echo ""
}

#############################################################################
# MAIN EXECUTION
#############################################################################

main() {
    clear

    print_banner "Platform Health Check"
    echo ""
    echo "Checking health of all detected services and components..."
    echo ""

    # Show detected platform
    echo -e "${BOLD}Detected Platform:${NC}"
    echo "  Control Panel: ${CYAN}${SYS_CONTROL_PANEL^^}${NC} v${SYS_CONTROL_PANEL_VERSION}"
    echo "  OS: ${CYAN}${SYS_OS_TYPE^^}${NC} ${SYS_OS_VERSION}"
    echo "  Web Server: ${CYAN}${SYS_WEB_SERVER^^}${NC}"
    echo "  Database: ${CYAN}${SYS_DB_TYPE^^}${NC}"
    echo ""

    # Run platform-specific checks
    case "$SYS_CONTROL_PANEL" in
        cpanel) check_cpanel_health ;;
        plesk) check_plesk_health ;;
        interworx) check_interworx_health ;;
        *) check_standalone_health ;;
    esac

    # Universal checks
    check_system_critical
    check_firewall_health
    check_php_health
    check_storage
    check_cloudflare_status

    # Summary
    echo ""
    print_section "Summary"
    echo ""
    echo "Health check complete. Review any ${RED}failures${NC} or ${YELLOW}warnings${NC} above."
    echo ""
}

# Run if sourced or executed
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    main "$@"
fi
