#!/usr/bin/env python3
# first_shred.py: which of two feeds delivers each shred first?
# Point one destination at each port below, then run this on that one machine: python3 first_shred.py [seconds]
import selectors, socket, struct, sys, time

FEEDS = {"current": 20001, "premium": 20002}   # feed name -> UDP port on this machine
SECONDS = int(sys.argv[1]) if len(sys.argv) > 1 else 60
HEADER = 83   # common shred header: signature 64, variant 1, slot 8, index 4, version 2, fec set 4

sel = selectors.DefaultSelector()
for name, port in FEEDS.items():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8 << 20)
    sock.bind(("0.0.0.0", port))
    sock.setblocking(False)
    sel.register(sock, selectors.EVENT_READ, name)

arrived = {}                          # (slot, index, variant) -> {feed: first arrival in ns}
packets = dict.fromkeys(FEEDS, 0)
end = time.monotonic() + SECONDS
while time.monotonic() < end:
    for key, _ in sel.select(timeout=1):
        while True:
            try:
                pkt = key.fileobj.recv(2048)
            except BlockingIOError:
                break
            now = time.perf_counter_ns()
            if len(pkt) < HEADER or pkt.startswith(b"SHREDCAST-VERIFY"):
                continue
            slot, index = struct.unpack_from("<QI", pkt, 65)
            arrived.setdefault((slot, index, pkt[64]), {}).setdefault(key.data, now)
            packets[key.data] += 1

a, b = FEEDS
both = [t for t in arrived.values() if a in t and b in t]
print("packets received:", packets)
print("shreds seen on both feeds:", len(both))
for first, second in ((a, b), (b, a)):
    lead = sorted((t[second] - t[first]) / 1e6 for t in both if t[first] < t[second])
    if lead:
        p95 = lead[min(len(lead) - 1, int(len(lead) * 0.95))]
        print(f"{first} first on {len(lead) / len(both):.0%} of them: median {lead[len(lead) // 2]:.2f} ms ahead, 95th percentile {p95:.2f} ms")
