"""Counts providerBatch spans by event_count, and the SQL work under the empty ones."""
import json
import sys
from collections import Counter

spans = []
with open(sys.argv[1]) as f:
    for line in f:
        try:
            r = json.loads(line)
        except ValueError:
            continue
        if r.get("type") == "effect-span":
            spans.append(r)

batches = [s for s in spans if s["name"] == "orchestrationV2.EventSink.providerBatch"]
empty = [s for s in batches if s["attributes"].get("orchestration_v2.event_count") == 0
         and s["attributes"].get("orchestration_v2.batch_writes") == 0]
empty_ids = {s["spanId"] for s in empty}
starts = [int(s["startTimeUnixNano"]) for s in batches]
window = (max(starts) - min(starts)) / 1e9 if starts else 0

children = {}
for s in spans:
    children.setdefault(s.get("parentSpanId"), []).append(s)

def descendants(span_id):
    for c in children.get(span_id, []):
        yield c
        yield from descendants(c["spanId"])

under_empty = Counter()
for sid in empty_ids:
    for d in descendants(sid):
        under_empty[d["name"]] += 1

flush = [s for s in spans if s["name"] == "orchestrationV2.ProviderCommitBatch.flush"]
durs = sorted(s["durationMs"] for s in empty)
print(f"providerBatch spans: {len(batches)}, empty (event_count=0, batch_writes=0): {len(empty)}")
print(f"window: {window:.1f} s, empty per second: {len(empty) / window if window else 0:.1f}")
print(f"ProviderCommitBatch.flush spans: {len(flush)}")
if durs:
    print(f"empty providerBatch duration median {durs[len(durs)//2]:.2f} ms")
print("event_count distribution:", Counter(s["attributes"].get("orchestration_v2.event_count") for s in batches).most_common(8))
print("spans under empty batches:")
for name, n in under_empty.most_common(10):
    print(f"  {n:6d} {name}")
