#!/usr/bin/env python3
"""netusage - per-interface usage by hour, from snapshot deltas stored in ~/.cache.
Usage: netusage [--snapshot] [--today] [--date YYYY-MM-DD] [--selftest]
  --snapshot records current /proc/net/dev byte counts (run from cron every
  few minutes). Plain `netusage` reads the stored snapshots and shows, per
  interface, how many bytes moved in each hour — the twist vs bandwidth:
  history, so "how much did we download between 2pm and 3pm?" is a lookup,
  not a guess. Counters reset on reboot; a drop between snapshots is
  treated as a reset and ignored.
"""
import argparse
import json
import os
import sys
from datetime import datetime

DEFAULT_DIR = os.path.expanduser("~/.cache/netusage")


def read_dev():
    out = {}
    try:
        with open("/proc/net/dev") as f:
            next(f)
            next(f)
            for line in f:
                if ":" not in line:
                    continue
                name, rest = line.split(":", 1)
                fields = rest.split()
                if len(fields) >= 9:
                    out[name.strip()] = (int(fields[0]), int(fields[8]))
    except OSError as e:
        print(f"netusage: cannot read /proc/net/dev: {e}", file=sys.stderr)
        return None
    return out


def load_snapshots(cache_dir):
    path = os.path.join(cache_dir, "snapshots.json")
    try:
        with open(path) as f:
            data = json.load(f)
        return data if isinstance(data, list) else []
    except (OSError, ValueError):
        return []


def save_snapshots(cache_dir, snaps):
    os.makedirs(cache_dir, exist_ok=True)
    path = os.path.join(cache_dir, "snapshots.json")
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(snaps, f)
    os.replace(tmp, path)


def do_snapshot(cache_dir):
    dev = read_dev()
    if dev is None:
        return 1
    snaps = load_snapshots(cache_dir)
    snaps.append({"ts": int(datetime.now().timestamp()),
                  "ifaces": {k: {"rx": v[0], "tx": v[1]} for k, v in dev.items()}})
    # keep the last 7 days of snapshots (bounded file)
    cutoff = int(datetime.now().timestamp()) - 7 * 86400
    snaps = [s for s in snaps if s["ts"] >= cutoff]
    save_snapshots(cache_dir, snaps)
    print(f"netusage: snapshot saved ({len(dev)} interfaces, {len(snaps)} stored)")
    return 0


def hourly(snaps, day):
    """Return {iface: {hour: (rx, tx)}} deltas for one calendar day."""
    per_hour = {}
    prev = None
    for snap in sorted(snaps, key=lambda s: s["ts"]):
        dt = datetime.fromtimestamp(snap["ts"])
        if dt.strftime("%Y-%m-%d") != day:
            prev = snap
            continue
        if prev is not None:
            hour = dt.hour
            for iface, vals in snap["ifaces"].items():
                old = prev["ifaces"].get(iface)
                if not old:
                    continue
                drx = vals["rx"] - old["rx"]
                dtx = vals["tx"] - old["tx"]
                if drx < 0 or dtx < 0:
                    continue  # counter reset (reboot); ignore this interval
                per_hour.setdefault(iface, {}).setdefault(hour, [0, 0])
                per_hour[iface][hour][0] += drx
                per_hour[iface][hour][1] += dtx
        prev = snap
    return per_hour


def human(n):
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024:
            return f"{n:.1f} {unit}"
        n /= 1024
    return f"{n:.1f} PB"


def show(cache_dir, day):
    snaps = load_snapshots(cache_dir)
    if not snaps:
        print(f"netusage: no snapshots yet — run `netusage --snapshot` (ideally from cron).")
        return 0
    per_hour = hourly(snaps, day)
    if not per_hour:
        todays = [x for x in snaps
                  if datetime.fromtimestamp(x["ts"]).strftime("%Y-%m-%d") == day]
        if todays:
            print(f"netusage: only {len(todays)} snapshot(s) for {day} -- "
                  f"hourly usage needs at least two "
                  f"(run --snapshot again later, ideally from cron).")
        else:
            print(f"netusage: no snapshots for {day} (have {len(snaps)} stored).")
        return 0
    print(f"netusage: usage by hour for {day} (from {len(snaps)} stored snapshots)")
    for iface in sorted(per_hour):
        print(f"\n{iface}:")
        total_rx = total_tx = 0
        for hour in sorted(per_hour[iface]):
            rx, tx = per_hour[iface][hour]
            total_rx += rx
            total_tx += tx
            print(f"  {hour:02d}:00  RX {human(rx):>10}  TX {human(tx):>10}")
        print(f"  TOTAL     RX {human(total_rx):>10}  TX {human(total_tx):>10}")
    return 0


def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        # Fabricate snapshots: lo moves 1000 RX / 500 TX in hour 10, 2000/1000 in hour 11.
        base = int(datetime(2026, 12, 3, 10, 0).timestamp())
        snaps = [
            {"ts": base, "ifaces": {"lo": {"rx": 10000, "tx": 5000}}},
            {"ts": base + 1800, "ifaces": {"lo": {"rx": 11000, "tx": 5500}}},
            {"ts": base + 3600, "ifaces": {"lo": {"rx": 13000, "tx": 6500}}},
        ]
        save_snapshots(d, snaps)
        per_hour = hourly(load_snapshots(d), "2026-12-03")
        assert per_hour["lo"][10] == [1000, 500], per_hour
        assert per_hour["lo"][11] == [2000, 1000], per_hour
        print("selftest: hourly deltas from fabricated snapshots: hour 10 RX 1000/TX 500, hour 11 RX 2000/TX 1000")
        show(d, "2026-12-03")
        # live snapshot path also works
        rc = do_snapshot(d)
        assert rc == 0
        print("selftest: hourly accounting + live snapshot — OK")
        return 0


def main():
    ap = argparse.ArgumentParser(description="netusage - per-interface usage by hour, from stored snapshots")
    ap.add_argument("--snapshot", action="store_true", help="record current counters (run from cron)")
    ap.add_argument("--today", action="store_true", help="show today's hourly usage (default)")
    ap.add_argument("--date", help="show hourly usage for YYYY-MM-DD")
    ap.add_argument("--cache-dir", default=DEFAULT_DIR, help="snapshot directory (default ~/.cache/netusage)")
    ap.add_argument("--selftest", action="store_true", help="hourly math on fabricated snapshots + one live snapshot")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if args.snapshot:
        return do_snapshot(args.cache_dir)
    day = args.date or datetime.now().strftime("%Y-%m-%d")
    return show(args.cache_dir, day)


if __name__ == "__main__":
    sys.exit(main())
