#!/usr/bin/env python3

import csv
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

OUT = Path(sys.argv[1])
OUT.mkdir(parents=True, exist_ok=True)

INTERVAL = 1.0

system_file = open(OUT / "system.csv", "w", newline="", buffering=1)
gpu_file = open(OUT / "gpu.csv", "w", newline="", buffering=1)

system = csv.writer(system_file)
gpu = csv.writer(gpu_file)

system.writerow([
    "timestamp",
    "cpu_busy_pct",
    "cpu_iowait_pct",
    "load1",
    "load5",
    "load15",
    "procs_running",
    "procs_blocked",
    "mem_used_gib",
    "mem_available_gib",
    "swap_used_gib",
    "dirty_mib",
    "writeback_mib",
    "psi_cpu_some_avg10",
    "psi_mem_some_avg10",
    "psi_io_some_avg10",
    "disk_read_mib_s",
    "disk_write_mib_s",
    "net_rx_mib_s",
    "net_tx_mib_s",
])

gpu.writerow([
    "timestamp",
    "gpu",
    "util_gpu_pct",
    "util_mem_pct",
    "memory_used_mib",
    "memory_free_mib",
    "power_w",
    "temp_c",
    "clock_sm_mhz",
])


def cpu_stats():
    vals = list(map(int, open("/proc/stat").readline().split()[1:]))
    while len(vals) < 8:
        vals.append(0)

    user, nice, system_, idle, iowait, irq, softirq, steal = vals[:8]

    total = sum(vals[:8])

    return total, idle, iowait


def proc_counts():
    running = 0
    blocked = 0

    with open("/proc/stat") as f:
        for line in f:
            if line.startswith("procs_running "):
                running = int(line.split()[1])
            elif line.startswith("procs_blocked "):
                blocked = int(line.split()[1])

    return running, blocked


def mem_stats():
    m = {}

    with open("/proc/meminfo") as f:
        for line in f:
            k, v = line.split(":", 1)
            m[k] = int(v.strip().split()[0])

    total = m["MemTotal"]
    avail = m["MemAvailable"]

    used = total - avail
    swap_used = m.get("SwapTotal", 0) - m.get("SwapFree", 0)

    return (
        used / 1024 / 1024,
        avail / 1024 / 1024,
        swap_used / 1024 / 1024,
        m.get("Dirty", 0) / 1024,
        m.get("Writeback", 0) / 1024,
    )


def psi(name):
    try:
        with open(f"/proc/pressure/{name}") as f:
            for line in f:
                if line.startswith("some "):
                    for part in line.split():
                        if part.startswith("avg10="):
                            return float(part.split("=")[1])
    except Exception:
        pass

    return 0.0


def disk_stats():
    read_sectors = 0
    write_sectors = 0

    for dev in os.listdir("/sys/block"):
        if dev.startswith(("loop", "ram", "zram", "sr")):
            continue

        try:
            vals = list(map(int, open(f"/sys/block/{dev}/stat").read().split()))

            # Linux block stat:
            # field 3 = sectors read
            # field 7 = sectors written
            read_sectors += vals[2]
            write_sectors += vals[6]
        except Exception:
            pass

    return read_sectors, write_sectors


def net_stats():
    rx = 0
    tx = 0

    with open("/proc/net/dev") as f:
        for line in f:
            if ":" not in line:
                continue

            iface, data = line.split(":", 1)
            iface = iface.strip()

            if iface == "lo":
                continue

            vals = data.split()
            rx += int(vals[0])
            tx += int(vals[8])

    return rx, tx


def gpu_stats(ts):
    try:
        out = subprocess.check_output([
            "nvidia-smi",
            "--query-gpu=index,utilization.gpu,utilization.memory,memory.used,memory.free,power.draw,temperature.gpu,clocks.sm",
            "--format=csv,noheader,nounits",
        ], text=True, timeout=3)

        for line in out.strip().splitlines():
            vals = [x.strip() for x in line.split(",")]
            gpu.writerow([ts] + vals)

        gpu_file.flush()

    except Exception as e:
        with open(OUT / "monitor-errors.log", "a") as f:
            f.write(f"{ts} GPU ERROR: {e}\n")


prev_cpu = cpu_stats()
prev_disk = disk_stats()
prev_net = net_stats()
prev_time = time.monotonic()

while True:
    try:
        time.sleep(INTERVAL)

        now = time.monotonic()
        dt = now - prev_time
        prev_time = now

        ts = datetime.now(timezone.utc).isoformat()

        current_cpu = cpu_stats()

        dt_total = current_cpu[0] - prev_cpu[0]
        dt_idle = current_cpu[1] - prev_cpu[1]
        dt_iowait = current_cpu[2] - prev_cpu[2]

        if dt_total > 0:
            cpu_busy = 100.0 * (dt_total - dt_idle - dt_iowait) / dt_total
            cpu_iowait = 100.0 * dt_iowait / dt_total
        else:
            cpu_busy = 0.0
            cpu_iowait = 0.0

        prev_cpu = current_cpu

        load1, load5, load15 = os.getloadavg()

        running, blocked = proc_counts()

        mem_used, mem_avail, swap_used, dirty, writeback = mem_stats()

        current_disk = disk_stats()

        read_mib = (
            (current_disk[0] - prev_disk[0]) * 512
            / 1024 / 1024 / dt
        )

        write_mib = (
            (current_disk[1] - prev_disk[1]) * 512
            / 1024 / 1024 / dt
        )

        prev_disk = current_disk

        current_net = net_stats()

        rx_mib = (
            (current_net[0] - prev_net[0])
            / 1024 / 1024 / dt
        )

        tx_mib = (
            (current_net[1] - prev_net[1])
            / 1024 / 1024 / dt
        )

        prev_net = current_net

        system.writerow([
            ts,
            round(cpu_busy, 2),
            round(cpu_iowait, 2),
            round(load1, 2),
            round(load5, 2),
            round(load15, 2),
            running,
            blocked,
            round(mem_used, 3),
            round(mem_avail, 3),
            round(swap_used, 3),
            round(dirty, 2),
            round(writeback, 2),
            psi("cpu"),
            psi("memory"),
            psi("io"),
            round(read_mib, 3),
            round(write_mib, 3),
            round(rx_mib, 3),
            round(tx_mib, 3),
        ])

        system_file.flush()

        gpu_stats(ts)

    except KeyboardInterrupt:
        break

    except Exception as e:
        with open(OUT / "monitor-errors.log", "a") as f:
            f.write(f"{datetime.now(timezone.utc).isoformat()} ERROR: {e}\n")
