#!/usr/bin/env python3
"""Collect server runtime stats (uptime, top, cgroup, mounts, hdd) and return as JSON."""

import json
import os
import subprocess


def cmd(args, splitlines=False):
    try:
        result = subprocess.run(
            args,
            capture_output=True,
            text=True,
            timeout=30,
        )
        out = (result.stdout + result.stderr).strip()

        if splitlines:
            return out.splitlines()

        return out

    except Exception as e:
        return f"ERROR: {e}"


def read_file(path):
    try:
        with open(path) as f:
            return f.read().strip().splitlines()
    except FileNotFoundError:
        return None


def disk_usage(path):
    """Total/used/available bytes for the filesystem at `path` (same figures as df)."""
    try:
        st = os.statvfs(path)
        return {
            "path": path,
            "total_bytes": st.f_blocks * st.f_frsize,
            "used_bytes": (st.f_blocks - st.f_bfree) * st.f_frsize,
            "available_bytes": st.f_bavail * st.f_frsize,
        }
    except Exception as e:
        return f"ERROR: {e}"


def main():
    stats = {}

    stats["uptime"] = cmd(["uptime"])
    stats["top"] = cmd(["sh", "-c", "top -b -n 1 | head -n 3"], splitlines=True)
    stats["cgroup"] = read_file("/proc/self/cgroup")
    stats["mounts"] = cmd(["mount"], splitlines=True)
    stats["hdd"] = disk_usage("/")

    print(json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()
