"""System resource monitoring route — /api/v1/system"""

import logging
import os
import shutil
import time
from typing import Any

from fastapi import APIRouter

logger = logging.getLogger(__name__)

router = APIRouter(tags=["system"])


def _read_meminfo() -> dict[str, int]:
    """Read memory info from /proc/meminfo (Linux only)."""
    values: dict[str, int] = {}
    try:
        with open("/proc/meminfo", encoding="utf-8") as f:  # noqa: ASYNC230
            for line in f:
                parts = line.split(":")
                if len(parts) == 2:
                    key = parts[0].strip()
                    value = parts[1].strip().split()[0]
                    values[key] = int(value) * 1024  # kB -> bytes
    except Exception as exc:
        logger.debug(f"Failed to read /proc/meminfo: {exc}")
    return values


@router.get("/system/resources")
async def get_system_resources() -> dict[str, Any]:
    """Return lightweight system resource usage.

    Uses only stdlib modules so it works without psutil. Values are best-effort
    and may be partial on platforms without /proc/meminfo.

    Note: This endpoint is intentionally NOT gated by SYSTEM_CONFIG. It is
    read-only monitoring data (CPU/memory/disk stats) that should be visible
    to any authenticated or dev-mode user. Gating it under SYSTEM_CONFIG
    caused 401 responses in dev mode, which the frontend's API client
    treated as session expiration and triggered an unwanted redirect to
    the login page. If stricter access control is required in the future,
    add a dedicated ``SYSTEM_VIEW`` permission rather than reusing
    ``SYSTEM_CONFIG``.
    """
    now = time.time()

    cpu_count = os.cpu_count() or 1
    loadavg = None
    if hasattr(os, "getloadavg"):
        try:
            loadavg = list(os.getloadavg())
        except Exception as exc:
            logger.debug(f"Failed to get loadavg: {exc}")

    meminfo = _read_meminfo()
    total_mem = meminfo.get("MemTotal", 0)
    free_mem = meminfo.get("MemAvailable") or meminfo.get("MemFree", 0)
    used_mem = total_mem - free_mem if total_mem else 0

    disk_total = 0
    disk_used = 0
    disk_free = 0
    try:
        du = shutil.disk_usage("/")
        disk_total = du.total
        disk_used = du.used
        disk_free = du.free
    except Exception as exc:
        logger.debug(f"Failed to get disk usage: {exc}")

    return {
        "cpu": {
            "count": cpu_count,
            "load_average": loadavg,
        },
        "memory": {
            "total_bytes": total_mem,
            "used_bytes": used_mem,
            "free_bytes": free_mem,
            "percent": round(used_mem / total_mem * 100, 1) if total_mem else None,
        },
        "disk": {
            "total_bytes": disk_total,
            "used_bytes": disk_used,
            "free_bytes": disk_free,
            "percent": round(disk_used / disk_total * 100, 1) if disk_total else None,
        },
        "timestamp": now,
    }
