#!/usr/bin/env python3
"""pingraph - ping a host and draw a latency graph over time.
Usage: pingraph HOST [-c COUNT] [-i SECONDS] [--selftest]
  Runs ping, parses each reply's time= value, and draws a live ASCII
  latency graph (one column per reply, height = latency) plus min/avg/max
  and a jitter figure. The twist vs plain ping: you see the shape — spikes,
  drift, and dropouts — instead of a scrolling wall of numbers.
"""
import argparse
import re
import shutil
import subprocess
import sys

TIME_RE = re.compile(r"time[=<]([\d.]+)\s*ms")
BLOCKS = " _.-~^#"


def ping_times(host, count, interval):
    """Yield ('ok', ms) or ('lost', None) per reply, using the system ping."""
    ping = shutil.which("ping")
    if not ping:
        raise RuntimeError("ping command not found")
    proc = subprocess.Popen(
        [ping, "-c", str(count), "-i", str(interval), host],
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    for line in proc.stdout:
        m = TIME_RE.search(line)
        if m:
            yield ("ok", float(m.group(1)))
        elif "packet loss" in line or "100% packet loss" in line:
            pass
    proc.wait()
    if proc.returncode not in (0, 1):
        raise RuntimeError(f"ping exited with code {proc.returncode}")


def draw(samples):
    """samples: list of float ms or None for lost. Prints a vertical graph."""
    ok = [s for s in samples if s is not None]
    if not ok:
        print("(no replies to graph)")
        return
    peak = max(ok)
    rows = 8
    print(f"latency graph (each column = one reply, peak {peak:.1f} ms; '.' = lost)")
    for r in range(rows, 0, -1):
        line = ""
        for s in samples:
            if s is None:
                line += "."
            else:
                level = int(s / peak * rows) if peak > 0 else 0
                line += "#" if level >= r else " "
        print(f"{peak * r / rows:7.1f} ms |{line}")
    print("         +" + "-" * len(samples))
    lost = sum(1 for s in samples if s is None)
    print(f"n={len(samples)} min={min(ok):.1f} avg={sum(ok)/len(ok):.1f} max={max(ok):.1f} ms  lost={lost}")
    if len(ok) > 1:
        jitter = sum(abs(ok[i] - ok[i - 1]) for i in range(1, len(ok))) / (len(ok) - 1)
        print(f"jitter (mean abs step): {jitter:.1f} ms")


def selftest():
    print("selftest: pinging 127.0.0.1, 4 packets")
    samples = [ms for _, ms in ping_times("127.0.0.1", 4, 0.2)]
    if not samples:
        print("selftest: FAIL — no replies from localhost")
        return 1
    draw(samples)
    print("selftest: graph drawn from live localhost pings — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="pingraph - ping a host and draw a latency graph over time")
    ap.add_argument("host", nargs="?", help="host to ping")
    ap.add_argument("-c", "--count", type=int, default=20, help="number of pings (default 20)")
    ap.add_argument("-i", "--interval", type=float, default=1.0, help="seconds between pings (default 1)")
    ap.add_argument("--selftest", action="store_true", help="ping 127.0.0.1 four times and draw the graph")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if not args.host:
        ap.error("HOST is required (or use --selftest)")
    try:
        samples = [ms for _, ms in ping_times(args.host, args.count, args.interval)]
    except RuntimeError as e:
        print(f"pingraph: {e}", file=sys.stderr)
        return 1
    if not samples:
        print(f"pingraph: no replies from {args.host}")
        return 1
    draw(samples)
    return 0


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