"""YakPanel - Monitor API"""
import psutil
from fastapi import APIRouter, Depends, Query

from app.api.auth import get_current_user
from app.models.user import User

router = APIRouter(prefix="/monitor", tags=["monitor"])


@router.get("/system")
async def monitor_system(current_user: User = Depends(get_current_user)):
    """Get system stats"""
    cpu = psutil.cpu_percent(interval=1)
    mem = psutil.virtual_memory()
    disk = psutil.disk_usage("/")
    return {
        "cpu_percent": cpu,
        "memory_percent": mem.percent,
        "memory_used_mb": round(mem.used / 1024 / 1024, 1),
        "memory_total_mb": round(mem.total / 1024 / 1024, 1),
        "disk_percent": disk.percent,
        "disk_used_gb": round(disk.used / 1024 / 1024 / 1024, 2),
        "disk_total_gb": round(disk.total / 1024 / 1024 / 1024, 2),
    }


@router.get("/processes")
async def monitor_processes(
    current_user: User = Depends(get_current_user),
    limit: int = Query(50, ge=1, le=200),
):
    """Get top processes by CPU usage"""
    procs = []
    for p in psutil.process_iter(["pid", "name", "username", "cpu_percent", "memory_percent", "status"]):
        try:
            info = p.info
            cpu = info.get("cpu_percent") or 0
            mem = info.get("memory_percent") or 0
            procs.append({
                "pid": info.get("pid"),
                "name": info.get("name") or "",
                "username": info.get("username") or "",
                "cpu_percent": round(cpu, 1),
                "memory_percent": round(mem, 1),
                "status": info.get("status") or "",
            })
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    procs.sort(key=lambda x: (x["cpu_percent"] or 0), reverse=True)
    return {"processes": procs[:limit]}


@router.get("/network")
async def monitor_network(current_user: User = Depends(get_current_user)):
    """Get network I/O stats"""
    net = psutil.net_io_counters()
    return {
        "bytes_sent": net.bytes_sent,
        "bytes_recv": net.bytes_recv,
        "packets_sent": net.packets_sent,
        "packets_recv": net.packets_recv,
        "bytes_sent_mb": round(net.bytes_sent / 1024 / 1024, 2),
        "bytes_recv_mb": round(net.bytes_recv / 1024 / 1024, 2),
    }
