try:
    import psutil
except ImportError:
    psutil = None
import time
import datetime
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

def get_system_status() -> str:
    """
    Returns a formatted string containing internal system status (CPU, RAM, usage).
    """
    if psutil is None:
        return "⚠️ Error: `psutil` library is not installed on the server. Please install it using `pip install psutil` to use this feature."

    try:
        # 1. System Info
        boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
        uptime = datetime.datetime.now() - boot_time
        uptime_str = str(uptime).split('.')[0] # Remove microseconds
        
        # 2. CPU
        cpu_percent = psutil.cpu_percent(interval=1)
        cpu_count = psutil.cpu_count()
        load_avg = [x / cpu_count for x in psutil.getloadavg()] # Normalize by core count roughly
        
        # 3. Memory
        ram = psutil.virtual_memory()
        swap = psutil.swap_memory()
        
        # 4. Disk
        disk = psutil.disk_usage('/')
        
        # 5. Top Processes
        # Get all processes
        procs = []
        for p in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_percent']):
            try:
                # Calculate valid CPU percent (some are > 100 on multi-core)
                p.info['cpu_percent'] = p.info['cpu_percent'] or 0.0
                procs.append(p.info)
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
                
        # Sort by CPU
        top_cpu = sorted(procs, key=lambda p: p['cpu_percent'], reverse=True)[:3]
        
        # Format Output
        dashboard = (
             f"🖥️ *System Status Application*\n"
             f"-----------------------------------\n"
             f"**Uptime**: {uptime_str}\n"
             f"**CPU**: {cpu_percent}% (Load: {load_avg[0]:.2f}, {load_avg[1]:.2f}, {load_avg[2]:.2f})\n"
             f"**Memory**: {ram.percent}% Used ({_bytes2human(ram.used)} / {_bytes2human(ram.total)})\n"
             f"**Swap**: {swap.percent}% Used ({_bytes2human(swap.used)})\n"
             f"**Disk (/)**: {disk.percent}% Used ({_bytes2human(disk.used)} / {_bytes2human(disk.total)})\n"
             f"-----------------------------------\n"
             f"*Top 3 CPU Processes:*\n"
        )
        
        for p in top_cpu:
            dashboard += f"• `{p['name']}` (PID {p['pid']}): {p['cpu_percent']}% CPU, {p['memory_percent']:.1f}% MEM\n"
            
        return dashboard
        
    except Exception as e:
        logger.error(f"System status failed: {e}")
        return f"❌ Error retrieving system status: {e}"

def _bytes2human(n):
    # http://code.activestate.com/recipes/578019
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return "%sB" % n
