"""Endpoint pour les statistiques système."""
from __future__ import annotations

import os
from pathlib import Path

import psutil
from fastapi import APIRouter
from pydantic import BaseModel

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


class SystemStats(BaseModel):
    """Statistiques système."""

    cpu_percent: float
    memory_mb: float
    memory_percent: float
    data_size_mb: float


def get_directory_size(path: Path) -> int:
    """Calcule la taille totale d'un répertoire en bytes."""
    total = 0
    if path.exists() and path.is_dir():
        for entry in path.rglob("*"):
            if entry.is_file():
                try:
                    total += entry.stat().st_size
                except (OSError, PermissionError):
                    pass
    return total


@router.get("", response_model=SystemStats)
def get_stats() -> SystemStats:
    """Retourne les statistiques système du backend."""
    # CPU et mémoire du process courant
    process = psutil.Process(os.getpid())
    cpu_percent = process.cpu_percent(interval=0.1)
    memory_info = process.memory_info()
    memory_mb = memory_info.rss / (1024 * 1024)

    # Mémoire système totale pour calculer le pourcentage
    total_memory = psutil.virtual_memory().total
    memory_percent = (memory_info.rss / total_memory) * 100

    # Taille des dossiers data et logs
    base_path = Path("/app/backend")
    if not base_path.exists():
        # Fallback pour le développement local
        base_path = Path(__file__).parent.parent.parent

    data_path = base_path / "data"
    logs_path = base_path / "logs"

    data_size = get_directory_size(data_path) + get_directory_size(logs_path)
    data_size_mb = data_size / (1024 * 1024)

    return SystemStats(
        cpu_percent=round(cpu_percent, 1),
        memory_mb=round(memory_mb, 1),
        memory_percent=round(memory_percent, 1),
        data_size_mb=round(data_size_mb, 1),
    )
