"""
Router pour les statistiques système
Fournit les métriques RAM et CPU du serveur IPWatch
"""
from fastapi import APIRouter
import psutil
from datetime import datetime

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


@router.get("/stats")
async def get_system_stats():
    """
    Récupère les statistiques système du serveur IPWatch

    Returns:
        dict: Statistiques RAM et CPU
            - ram_percent: Pourcentage de RAM utilisée
            - ram_used: RAM utilisée en MB
            - ram_total: RAM totale en MB
            - ram_available: RAM disponible en MB
            - cpu_percent: Pourcentage d'utilisation CPU
            - cpu_count: Nombre de cœurs CPU
            - timestamp: Horodatage de la mesure
    """
    # Statistiques mémoire
    memory = psutil.virtual_memory()

    # Statistiques CPU (moyenne sur 1 seconde)
    cpu_percent = psutil.cpu_percent(interval=1)

    # Informations processus IPWatch
    process = psutil.Process()
    process_memory = process.memory_info()

    return {
        # RAM système
        "ram_percent": round(memory.percent, 1),
        "ram_used": round(memory.used / (1024 * 1024), 1),  # MB
        "ram_total": round(memory.total / (1024 * 1024), 1),  # MB
        "ram_available": round(memory.available / (1024 * 1024), 1),  # MB

        # CPU système
        "cpu_percent": round(cpu_percent, 1),
        "cpu_count": psutil.cpu_count(),

        # Processus IPWatch
        "process_ram_mb": round(process_memory.rss / (1024 * 1024), 1),  # MB
        "process_cpu_percent": round(process.cpu_percent(interval=0.1), 1),

        # Timestamp
        "timestamp": datetime.now().isoformat()
    }


@router.get("/uptime")
async def get_uptime():
    """
    Récupère l'uptime du système

    Returns:
        dict: Informations sur l'uptime
    """
    import time
    boot_time = psutil.boot_time()
    uptime_seconds = time.time() - boot_time

    return {
        "uptime_seconds": int(uptime_seconds),
        "uptime_hours": round(uptime_seconds / 3600, 1),
        "boot_time": datetime.fromtimestamp(boot_time).isoformat()
    }
