#!/bin/bash
# -----------------------------------------------------------------------
# Dynasty Module: Universal Pulse (v1.1.1 - Memory Fix)
# -----------------------------------------------------------------------

if [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macOS"
    CPU_LOAD=$(sysctl -n vm.loadavg | awk '{print $2}')
    
    # --- Advanced Mac Memory Math ---
    # Total Physical RAM in bytes
    MEM_TOTAL_BYTES=$(sysctl -n hw.memsize)
    MEM_TOTAL_GB=$((MEM_TOTAL_BYTES / 1024 / 1024 / 1024))
    
    # Get Page Size (usually 4096 or 16384 on M1)
    PAGE_SIZE=$(vm_stat | grep "page size of" | awk '{print $8}')
    
    # Get Free and Speculative pages (Both are essentially "Available")
    PAGES_FREE=$(vm_stat | grep "Pages free" | awk '{print $3}' | sed 's/\.//')
    PAGES_SPEC=$(vm_stat | grep "Pages speculative" | awk '{print $3}' | sed 's/\.//')
    
    # Calculate Available GB
    MEM_FREE_BYTES=$(((PAGES_FREE + PAGES_SPEC) * PAGE_SIZE))
    MEM_FREE_GB=$((MEM_FREE_BYTES / 1024 / 1024 / 1024))
    
    # Final Used Calculation
    MEM_USED_GB=$((MEM_TOTAL_GB - MEM_FREE_GB))
    
    UPTIME=$(uptime | sed -E 's/.*up ([^,]+),.*/\1/' | xargs)
    DISK=$(df -h / | awk 'NR==2 {print $5}')
else
    OS="Linux"
    CPU_LOAD=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')"%"
    MEM_TOTAL_GB=$(free -g | awk '/^Mem:/{print $2}')
    MEM_USED_GB=$(free -g | awk '/^Mem:/{print $3}')
    UPTIME=$(uptime -p | sed 's/up //')
    DISK=$(df -h / | awk 'NR==2 {print $5}')
fi

# --- Dashboard Construction ---
DASHBOARD="🐉 DYNASTY SYSTEM PULSE ($OS)
-------------------------------------
🕒 UPTIME:    $UPTIME
🚀 CPU LOAD:  $CPU_LOAD
🧠 MEMORY:    ${MEM_USED_GB}GB / ${MEM_TOTAL_GB}GB
💾 DISK:      $DISK Used
-------------------------------------"

# --- Display Logic ---
if [[ "$OS" == "macOS" ]]; then
    osascript -e "display dialog \"$DASHBOARD\" with title \"Dynasty Diagnostics\" buttons {\"Close\"} default button \"Close\"" >/dev/null 2>&1
else
    if command -v whiptail >/dev/null 2>&1; then
        whiptail --title "Dynasty Diagnostics" --msgbox "$DASHBOARD" 15 50
    else
        echo -e "$DASHBOARD"
    fi
fi