#!/usr/bin/env python3
"""
Quick local bandwidth monitor.
Run this while you use the PC normally. It prints live down/up speed
every few seconds, and prints a summary (avg / peak) when you stop it
with Ctrl+C.

Optional: run it for a while during your busiest hours to get a
realistic peak estimate, not just an idle-desktop number.
"""

import time
import psutil

INTERVAL = 2  # seconds between samples


def to_mbps(bytes_per_sec):
    return bytes_per_sec * 8 / 1_000_000


def main():
    print("Monitoring network usage. Use the PC normally. Press Ctrl+C to stop and see summary.\n")
    print(f"{'time':<10} {'down (Mbps)':<14} {'up (Mbps)':<12}")

    down_samples = []
    up_samples = []

    prev = psutil.net_io_counters()
    prev_time = time.time()

    try:
        while True:
            time.sleep(INTERVAL)
            now_counters = psutil.net_io_counters()
            now_time = time.time()
            elapsed = max(now_time - prev_time, 0.001)

            down_bps = (now_counters.bytes_recv - prev.bytes_recv) / elapsed
            up_bps = (now_counters.bytes_sent - prev.bytes_sent) / elapsed

            down_mbps = to_mbps(down_bps)
            up_mbps = to_mbps(up_bps)

            down_samples.append(down_mbps)
            up_samples.append(up_mbps)

            print(f"{time.strftime('%H:%M:%S'):<10} {down_mbps:<14.2f} {up_mbps:<12.2f}")

            prev, prev_time = now_counters, now_time

    except KeyboardInterrupt:
        print("\n\n--- Summary ---")
        if not down_samples:
            print("No samples collected yet.")
            return

        print(f"Samples collected: {len(down_samples)} over ~{len(down_samples) * INTERVAL}s")
        print(f"Download: avg {sum(down_samples)/len(down_samples):.2f} Mbps | "
              f"peak {max(down_samples):.2f} Mbps")
        print(f"Upload:   avg {sum(up_samples)/len(up_samples):.2f} Mbps | "
              f"peak {max(up_samples):.2f} Mbps")
        print("\nRough office estimate:")
        print("  multiply the AVG per PC by number of PCs for a baseline,")
        print("  and use the PEAK per PC x number of PCs as a rough worst-case ceiling")
        print("  (real worst-case will be lower since PCs rarely peak all at once).")


if __name__ == "__main__":
    main()