#!/usr/bin/env python3
"""Census of track gaps in the 4 hand jobs: how many short gaps (<=5 frames)
gap-filling could actually close. Read-only on boxes.json."""
import json, os, collections

BASE = "/home/agent/.claude/workspace/project/data/out"
JOBS = {
    "shipin1": "c3de403cfd15",
    "shipin2": "4e8924d45d4b",
    "shipin3": "fe165602b721",
    "shipin4": "e9ff7e814d64",
}

for stem, jid in JOBS.items():
    d = os.path.join(BASE, jid)
    bj = next(os.path.join(d, f) for f in os.listdir(d) if f.endswith(".boxes.json"))
    rows = json.load(open(bj))
    tracks = collections.defaultdict(list)
    for r in rows:
        for box, i in zip(r.get("boxes", []), r.get("ids", [])):
            tracks[i].append(r["frame"])
    gaps = collections.Counter()
    fillable_frames = 0
    for tid, frames in tracks.items():
        frames = sorted(set(frames))
        for a, b in zip(frames, frames[1:]):
            g = b - a - 1
            if g <= 0:
                continue
            if g == 1:
                gaps["1"] += 1
            elif g <= 5:
                gaps["2-5"] += 1
            elif g <= 30:
                gaps["6-30"] += 1
            else:
                gaps[">30"] += 1
            if g <= 5:
                fillable_frames += g
    print(f"{stem}: frames={len(rows)} tracks={len(tracks)} "
          f"gaps 1f={gaps['1']} 2-5f={gaps['2-5']} 6-30f={gaps['6-30']} >30f={gaps['>30']} "
          f"fillable_frames(<={5}f)={fillable_frames}")
