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

import json
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 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)

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


if __name__ == "__main__":
    main()
