try:
    import psutil
except ImportError:
    psutil = None
import signal
from typing import List, Dict
from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

def kill_process(pid: int, signal_type: str = "SIGTERM") -> str:
    """
    Terminates a process by PID. By default uses SIGTERM (graceful).
    
    Args:
        pid: Process ID.
        signal_type: "SIGTERM" (default) or "SIGKILL" (force).
        
    Returns:
        Status message.
    """
    if psutil is None:
        return "⚠️ Error: `psutil` library is not installed."

    try:
        if not psutil.pid_exists(pid):
            return f"❌ Process with PID {pid} does not exist."
            
        p = psutil.Process(pid)
        name = p.name()
        
        logger.info(f"Killing process {pid} ({name}) with {signal_type}")
        
        if signal_type == "SIGKILL":
            p.kill()
        else:
            p.terminate()
            
        return f"✅ Sent {signal_type} to process {pid} ({name})."
        
    except psutil.AccessDenied:
        return f"❌ Access Denied: Cannot kill PID {pid} (Root privileges required?)"
    except Exception as e:
        logger.error(f"Kill process failed: {e}")
        return f"❌ Error killing process: {e}"

def get_process_list(filter_name: str = None, limit: int = 15) -> str:
    """
    Returns a formatted table of running processes.
    """
    if psutil is None:
        return "⚠️ Error: `psutil` library is not installed."

    try:
        matches = []
        for p in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_percent', 'status']):
            try:
                p_info = p.info
                if filter_name:
                    if filter_name.lower() not in p_info['name'].lower():
                        continue
                matches.append(p_info)
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
        
        # Sort by CPU usage DESC
        matches.sort(key=lambda x: x.get('cpu_percent', 0), reverse=True)
        
        count = len(matches)
        matches = matches[:limit]
        
        output = f"📊 **Process List** ({count} total found, showing top {len(matches)})\n"
        output += f"`{'PID':<6} {'USER':<10} {'CPU%':<6} {'MEM%':<6} {'STATUS':<10} {'NAME'}`\n"
        output += "-" * 60 + "\n"
        
        for p in matches:
            cpu = f"{p['cpu_percent'] or 0}%"
            mem = f"{p['memory_percent'] or 0:.1f}%"
            user = (p['username'] or 'unknown')[:10]
            status = p['status'][:10]
            
            output += f"`{p['pid']:<6} {user:<10} {cpu:<6} {mem:<6} {status:<10} {p['name']}`\n"
            
        if count > limit:
            output += f"... and {count - limit} more."
            
        return output
        
    except Exception as e:
        logger.error(f"List processes failed: {e}")
        return f"❌ Error listing processes: {e}"
