#!/usr/bin/env python3
# stopwatch - terminal stopwatch with laps
# Usage: stopwatch [--duration SECONDS] [--laps N]
#   Interactive: press Enter for a lap, Ctrl-C (or EOF) to stop and see the summary.
#   --duration runs non-interactively for N seconds and prints the elapsed time.
import argparse, sys, time

def fmt(sec):
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    return f"{int(h):02d}:{int(m):02d}:{s:05.2f}"

def selftest():
    t0 = time.monotonic()
    time.sleep(0.3)
    el = time.monotonic() - t0
    assert 0.3 <= el < 1.0, el
    assert fmt(3661.5) == "01:01:01.50"
    assert fmt(65.25) == "00:01:05.25"
    print(f"stopwatch selftest: ok (0.3s timed at {el:.2f}s, formatting)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="stopwatch",
        description="Terminal stopwatch with laps. Enter = lap, Ctrl-C = stop.")
    p.add_argument("--duration", type=float, help="run non-interactively for N seconds")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.duration is not None:
        t0 = time.monotonic()
        time.sleep(a.duration)
        print(f"elapsed: {fmt(time.monotonic() - t0)}")
        return 0
    print("stopwatch running — Enter = lap, Ctrl-C = stop")
    t0 = time.monotonic()
    last = t0
    laps = []
    try:
        while True:
            line = sys.stdin.readline()
            if not line:
                break
            now = time.monotonic()
            laps.append((now - t0, now - last))
            last = now
            print(f"lap {len(laps)}: total {fmt(laps[-1][0])}  split {fmt(laps[-1][1])}")
    except KeyboardInterrupt:
        pass
    total = time.monotonic() - t0
    print(f"\nstopped: {fmt(total)}")
    for i, (tot, split) in enumerate(laps, 1):
        print(f"  lap {i}: total {fmt(tot)}  split {fmt(split)}")
    return 0

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