#!/usr/bin/env python3
"""scoreboard_highlights.py — cricket highlights from the scoreboard overlay. No API, no spend.

A broadcast scoreboard already carries the whole match. The overs counter ticks once per legal
ball and the total says what that ball scored, so finding every boundary in six hours of
footage is a matter of watching ~150 pixels change — not of understanding video. Nothing here
calls a model or a network: the only outside processes are ffmpeg and ffprobe.

  sample     one pass over the video at 1 fps, keeping only the score cell (a 91-minute part
             is about 29 MB of gray pixels).
  detect     the cell is FOUND, not assumed: the blue block in the lower band locates it, so
             another 1280×720 FrogBox feed needs no flags. `--cell` overrides.
  change     a ball is a frame where the cell changed. Measured over a 600-second window of
             the 2026-09-16 match: 15 of 15 deliveries, no false positives. A real update
             moves 240–975 pixels, a partial redraw 40–100, an untouched cell 0.
  read       the two frames either side of the change are read (overlay_read.py) and the
             delta says what the ball did — four, six, wicket, wide, dot.
  anchor     the scorer is 5.5–16 s behind the action, so the CHANGE is not the moment. The
             bat-on-ball transient in the audio is, when there is one; otherwise a fixed lead.
  cut        the windows are padded, merged and re-encoded into two reels, with an EDL and a
             filmstrip beside each.

Usage:
  scoreboard_highlights.py --video V --out DIR [--cell x,y,w,h] [--templates PATH]
      [--start S] [--end E] [--pre 6] [--post 4] [--lag 11]
      [--pad-pre 1.0] [--pad-post 1.5] [--min 3.0] [--types four,six,wicket] [--dry-run]
      [--eval verified.json] [--eval-boundaries boundaries-final.json] [--tolerance 6]
      [--build-templates DIR LABELS]...

Exit 0 ok (a skipped reel is a note) · 2 bad input · 4 refusal (no overlay found AND the cell
never changes, with no --cell; or the --eval bar was not met).
"""
from __future__ import annotations

import argparse
import json
import math
import os
import subprocess
import sys
import tempfile
import time
from typing import Callable, Sequence

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
SKILL = os.path.abspath(os.path.join(HERE, ".."))
sys.path.insert(0, HERE)

from overlay_read import (  # noqa: E402
    State, commit_policy, decode, hydrate_templates, load_templates, outcome, overs_of,
    parse_cell, parse_state, prior_ok, templates_from_labels,
)

FFMPEG = os.environ.get("FFMPEG_FULL") or os.environ.get("FFMPEG_BIN") or "ffmpeg"
FFPROBE = os.environ.get("FFPROBE_BIN") or "ffprobe"
DEFAULT_TEMPLATES = os.path.join(SKILL, "references", "frogbox-templates.json")

# --- constants -------------------------------------------------------------------------
# The FrogBox read cell at 1280×720, which `detect_overlay` reproduces from the blue block.
FROGBOX_CELL = (645, 651, 155, 34)
# How the read cell sits inside the blue block: (x, y, w, h) as fractions of the block.
READ_CELL_RATIOS = (0.51, 0.28, 0.50, 0.45)
# A band row carrying the block, and a column solidly inside it.
BLUE_ROW_FRAC, BLUE_COL_FRAC = 0.10, 0.60
# A block narrower than this fraction of the frame, or shorter than this fraction of the band,
# is not the score block — it is a caption strip or the edge of a graphic.
MIN_BLOCK_FRAC = 0.10
MIN_BLOCK_H_FRAC = 0.25
# Where in the video to look for the overlay. Nine points, not three: on part 2 of the
# 2026-09-16 match every one of 25/50/75% landed on a moment when a bowling-figures panel
# covered one end of the block, and the cell came back 118 px wide instead of 156.
PROBE_FRACTIONS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
# A pixel has changed when it moves this far in gray.
DIFF_GRAY = 40
# Area FRACTIONS of the cell, not pixel counts, so --cell on another resolution still works.
# A real score update moves 240–975 px of a 5 270 px cell (4.6–18%); a partial redraw 40–100.
STRONG_FRAC, WEAK_FRAC = 0.03, 0.005
# Runs and then the wicket, or a wide and then its correction, are entered seconds apart by one
# pair of hands. Inside this window they are ONE ball.
MERGE_S = 6
# THE WINDOW IS ANCHORED ON THE OVERLAY, NOT ON THE AUDIO, and it is long on purpose.
#
# The scoreboard says exactly WHICH ball and exactly WHAT happened. It says only roughly WHEN:
# the keystroke lands anywhere from about 3 s to 25 s after the run-up starts, and once in this
# match 53 s after. Nothing in the picture recovers that, so the window runs back far enough to
# hold the ball whatever the lag was. The price is a long clip, and that is the trade.
#
# Hanging it on the loudest transient instead is what made the reels worse to watch. When the
# scorer is quick the search band reaches into the PREVIOUS delivery, the loudest sound in it is
# that ball, and the clip lands one ball early — thirteen seconds of a batter waiting, ending
# just as the run-up starts. Measured against the paid run-up times for all 61 boundaries of
# this match: overlay-anchored holds the run-up AND the shot 57 times, audio-trimmed 50.
PRE_S, POST_S = 26.0, 2.0
# Retained for the reported anchor estimate only. The clip no longer depends on it.
LAG_S = 13.0
# `--audio-trim` is OPT-IN and off by default, for the reason above. With it on, the strongest
# transient inside this band may pull the START of the window forward; the band stops at t−13
# so it cannot reach back into the previous ball.
AUDIO_TRIM_BAND = (13.0, 3.0)
AUDIO_TRIM_PRE = 6.0
# A transient is this many times the running background, and two may not sit closer than this.
RATIO, MIN_GAP_S = 4.0, 2.0
# planWindows defaults, shared with `vclaw video match-highlights`.
PAD_PRE, PAD_POST, MIN_WINDOW_S = 1.0, 1.5, 3.0
FILMSTRIP = {"interval": 8, "width": 160, "columns": 15}
# `unknown` is in the default reel on purpose: an unreadable STRONG change is the overlay
# animating, which is what it does on a dismissal, and a highlights reel that silently drops a
# wicket is worse than one carrying a few seconds of nothing. Runs of them are already gone.
DEFAULT_TYPES = ("four", "six", "wicket", "unknown")
# A run of this many unreadable changes in a row is the overlay being GONE — an innings
# break, an interval — not a run of odd deliveries. Measured across the four parts of the
# 2026-09-16 match, unreadable events come in runs of one or two (six of them, all real
# glitches beside readable balls) or a run of 198 (the innings break). Nothing in between.
UNKNOWN_RUN_DROP = 3
# When the cell never decodes, two different things may have happened, and they have opposite
# fixes. A match being read with the wrong font changes the cell about once a ball — the
# reference parts average one change every 44 s. A stretch with no scoreboard in it at all
# changes a couple of times in the whole pass (part 5, the static scorecard: twice in 512 s).
# So a refusal needs BOTH a handful of changes and a rate that looks like cricket.
REFUSE_MIN_CHANGES = 3
REFUSE_MIN_RATE_S = 120.0
# How many frames after a change to keep trying. The overlay fades its new value in over a
# frame or two, so the very next frame is sometimes still mid-animation and reads as nothing.
SETTLE_FRAMES = 3
# Audio is read in 16-bit mono at this rate, in 10 ms frames.
AUDIO_RATE = 16000
AUDIO_FRAME_MS = 10
AUDIO_BG_S = 1.0
EVAL_DEDUPE_S = 4.0
EVAL_TOLERANCE_S = 6.0
EVAL_MIN_RECALL = 0.95
# What the method actually guarantees: the ball is somewhere in the reel that gets rendered.
EVAL_MIN_CONTAINS_SHOT = 0.90
# What "the clip shows the ball" means, in seconds after the run-up starts. A delivery is a
# run-up and then a shot; a clip that holds the first but not the second is the wrong clip, and
# a coverage measure that only asked whether the ball time fell somewhere inside a padded
# window scored those as hits. Both marks must be inside the RENDERED window.
SHOT_LEAD_S, SHOT_END_S = 1.5, 8.0
# How much worse pass two of the template build may read back before pass one is kept instead.
TEMPLATE_PASS_TOLERANCE = 0.01


def say(msg: str) -> None:
    print(f"scoreboard: {msg}", file=sys.stderr)


Runner = Callable[[Sequence[str]], bytes]


def run(args: Sequence[str], runner: Runner | None = None) -> bytes:
    """The ONE way this file reaches ffmpeg/ffprobe. Tests inject `runner` and spawn nothing."""
    if runner is not None:
        return runner(list(args))
    proc = subprocess.run(list(args), capture_output=True)
    if proc.returncode != 0:
        raise RuntimeError(f"{os.path.basename(args[0])} failed ({proc.returncode}): "
                           f"{proc.stderr[-400:].decode(errors='replace')}")
    return proc.stdout


# --- probe & overlay detection ---------------------------------------------------------
def probe(video: str, runner: Runner | None = None) -> dict:
    """{width, height, duration} for the video."""
    out = run([FFPROBE, "-v", "error", "-select_streams", "v:0", "-show_entries",
               "stream=width,height:format=duration", "-of", "json", video], runner)
    doc = json.loads(out.decode() or "{}")
    stream = (doc.get("streams") or [{}])[0]
    fmt = doc.get("format") or {}
    try:
        duration = float(fmt.get("duration") or 0.0)
    except (TypeError, ValueError):
        duration = 0.0
    return {"width": int(stream.get("width") or 0), "height": int(stream.get("height") or 0),
            "duration": duration}


def _band_frame(video: str, at: float, width: int, y0: int, band_h: int,
                runner: Runner | None) -> np.ndarray | None:
    raw = run([FFMPEG, "-v", "error", "-ss", f"{at:.3f}", "-i", video, "-frames:v", "1",
               "-vf", f"crop={width}:{band_h}:0:{y0},format=rgb24", "-f", "rawvideo", "-"], runner)
    need = width * band_h * 3
    if len(raw) < need:
        return None
    return np.frombuffer(raw[:need], dtype=np.uint8).reshape(band_h, width, 3)


def _longest_run(flags: np.ndarray) -> tuple[int, int] | None:
    best = None
    x, n = 0, len(flags)
    while x < n:
        if flags[x]:
            x0 = x
            while x < n and flags[x]:
                x += 1
            if best is None or (x - x0) > (best[1] - best[0]):
                best = (x0, x)
        else:
            x += 1
    return best


def blue_cell(band: np.ndarray) -> tuple[int, int, int, int] | None:
    """The score block inside the lower band, in BAND coordinates.

    Rows first, then columns. The block is a flattened hexagon — white chevrons bite into both
    ends — so a column fraction taken over the whole band height never reaches the edges and
    the box comes back ~110 px short. Finding the rows the block occupies first, and only then
    the columns that are solidly blue across them, recovers the whole width.
    """
    b = band[:, :, 2].astype(np.int16)
    r = band[:, :, 0].astype(np.int16)
    blue = (b - r > 60) & (b > 140)
    rows = np.flatnonzero(blue.mean(axis=1) >= BLUE_ROW_FRAC)
    if rows.size == 0:
        return None
    y0, y1 = int(rows[0]), int(rows[-1]) + 1
    if (y1 - y0) < MIN_BLOCK_H_FRAC * blue.shape[0]:
        return None
    cols = _longest_run(blue[y0:y1].mean(axis=0) >= BLUE_COL_FRAC)
    if cols is None or (cols[1] - cols[0]) < MIN_BLOCK_FRAC * blue.shape[1]:
        return None
    return cols[0], y0, cols[1] - cols[0], y1 - y0


def read_cell_of(cell: tuple[int, int, int, int], band_y0: int) -> tuple[int, int, int, int]:
    """The blue block → the columns the score is actually drawn in, in FRAME coordinates.

    The ratios are measured against the WHOLE block, FrogBox strip included, because that is
    what `blue_cell` returns: on the 2026-09-16 feed the block is (486, 631, 310, 76) and this
    lands on (645, 651, 155, 34) — the cell the 544-crop read-back was measured with.
    """
    x0, y0, w, h = cell
    rx, ry, rw, rh = READ_CELL_RATIOS
    return (int(round(x0 + rx * w)), int(round(band_y0 + y0 + ry * h)),
            int(round(rw * w)), int(round(rh * h)))


def detect_overlay(video: str, info: dict, runner: Runner | None = None) -> dict:
    """Find the score cell by looking at the picture, at nine points across the video.

    The overlay is absent during drinks and between innings, so one sample is not enough; the
    first frame that yields a cell wins and the others are compared against it. Nothing found
    means the FrogBox default plus a note — never a silent guess at a different geometry.
    """
    width, height = info["width"], info["height"]
    notes: list[str] = []
    if width <= 0 or height <= 0:
        return {"detected": False, "blueCell": None, "cell": list(FROGBOX_CELL),
                "frameSize": [width, height], "sampledAt": [],
                "notes": ["no video stream dimensions: using the FrogBox default cell"]}
    band_y0 = int(0.83 * height)
    band_h = height - band_y0
    seen: list[tuple[float, tuple[int, int, int, int]]] = []
    sampled: list[float] = []
    duration = info.get("duration") or 0.0
    for fraction in PROBE_FRACTIONS:
        at = max(0.0, duration * fraction)
        sampled.append(round(at, 2))
        try:
            band = _band_frame(video, at, width, band_y0, band_h, runner)
        except RuntimeError as exc:
            notes.append(f"overlay probe at {at:.0f}s failed: {str(exc)[:80]}")
            continue
        if band is None:
            continue
        cell = blue_cell(band)
        if cell is not None:
            seen.append((at, cell))
    # The WIDEST block wins. A sample taken while a bowling-figures panel or a replay wipe
    # covers one end returns a short box, and averaging it in would shift the cell off the
    # digits; the fullest view of the block is the one that is not covered.
    found = max((cell for _at, cell in seen), key=lambda c: c[2], default=None)
    if found is not None:
        agreed = sum(1 for _at, cell in seen
                     if abs(cell[0] - found[0]) <= 10 and abs(cell[2] - found[2]) <= 10)
        notes.append(f"the score block was fully visible in {agreed} of "
                     f"{len(PROBE_FRACTIONS)} probe frames")
    if found is None:
        notes.append("no blue score block found: using the FrogBox default cell")
        return {"detected": False, "blueCell": None, "cell": list(FROGBOX_CELL),
                "frameSize": [width, height], "sampledAt": sampled, "notes": notes}
    return {"detected": True, "blueCell": [int(v) for v in found],
            "cell": list(read_cell_of(found, band_y0)),
            "frameSize": [width, height], "sampledAt": sampled, "notes": notes}


# --- sampling --------------------------------------------------------------------------
def sample_cell(video: str, cell: Sequence[int], start: float, end: float,
                runner: Runner | None = None) -> np.ndarray:
    """One ffmpeg pass → uint8[N, h, w], one gray frame of the cell per second."""
    x, y, w, h = (int(v) for v in cell)
    args = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}"]
    if end > start:
        args += ["-t", f"{end - start:.3f}"]
    args += ["-i", video, "-vf", f"fps=1,crop={w}:{h}:{x}:{y},format=gray",
             "-f", "rawvideo", "-"]
    raw = run(args, runner)
    frame = w * h
    count = len(raw) // frame
    if count == 0:
        return np.zeros((0, h, w), dtype=np.uint8)
    return np.frombuffer(raw[:count * frame], dtype=np.uint8).reshape(count, h, w)


def change_events(frames: np.ndarray, merge_s: float = MERGE_S) -> list[dict]:
    """Frames → the moments the cell was rewritten.

    Two thresholds, both as a fraction of the cell's area: `weak` is any redraw at all and
    `strong` is a real score update. A run of consecutive changed frames is ONE change (the
    overlay fades in over two or three frames), and changes within `merge_s` are one event —
    runs and then the wicket are two keystrokes of the same ball.
    """
    if frames.ndim != 3 or len(frames) < 2:
        return []
    area = frames.shape[1] * frames.shape[2]
    weak, strong = WEAK_FRAC * area, STRONG_FRAC * area
    diff = np.abs(frames[1:].astype(np.int16) - frames[:-1].astype(np.int16))
    px = (diff > DIFF_GRAY).sum(axis=(1, 2))

    changes: list[tuple[int, float]] = []
    k = 0
    while k < len(px):
        if px[k] >= weak:
            k0, peak = k, float(px[k])
            while k < len(px) and px[k] >= weak:
                peak = max(peak, float(px[k]))
                k += 1
            changes.append((k0 + 1, peak))       # px[k] compares frame k+1 with frame k
        else:
            k += 1
    events: list[dict] = []
    for index, peak in changes:
        if events and (index - events[-1]["kLast"]) <= merge_s:
            events[-1]["kLast"] = index
            events[-1]["px"] = max(events[-1]["px"], peak)
            events[-1]["strong"] = events[-1]["strong"] or peak >= strong
            continue
        events.append({"kFirst": index, "kLast": index, "px": peak, "strong": peak >= strong})
    for event in events:
        event["px"] = int(event["px"])
        event["t"] = event["kFirst"] - 0.5
    return events


def read_states(frames: np.ndarray, events: list[dict], templates: dict,
                offset: float = 0.0) -> tuple[list[dict], list[dict], list[dict], list[str], dict]:
    """Read the cell either side of each change and keep the ones that moved the match on.

    A weak change that decodes to the same state is the overlay redrawing itself, not a ball,
    so it is dropped. A strong change the reader could not decode is KEPT with a null score —
    something happened there and the operator should see it.
    """
    kept: list[dict] = []
    innings: list[dict] = []
    corrections: list[dict] = []
    notes: list[str] = []
    if len(frames) == 0:
        return kept, innings, corrections, ["no frames sampled"], {"readable": 0, "changes": 0}

    first = parse_cell(frames[0], templates)
    prev, _text, flag = decode(first, None)
    if flag:
        prev = None
    pending: State | None = None
    pending_at: float | None = None
    pending_event: dict | None = None
    last_good: State | None = prev
    readable = 1 if prev is not None else 0
    setup_noise = 0          # strong changes before any score existed: the overlay being drawn
    baseline_reads = 0       # the read that first established a score: a baseline, not a ball

    def settled(k_last: int, against: State | None) -> tuple[State | None, str, str]:
        """The first of the next few frames that decodes to a NEW state.

        The value fades in, so the frame immediately after the change is sometimes still
        mid-animation: it reads as nothing, or it still reads the old score. Either way the
        event comes out as `unknown` and the ball is lost from the reel, which is why the next
        couple of frames are tried before giving up.
        """
        fallback: tuple[State | None, str, str] | None = None
        for step in range(1, SETTLE_FRAMES + 1):
            index = min(len(frames) - 1, k_last + step)
            read = parse_cell(frames[index], templates)
            state, text, flag = decode(read, against)
            # Keep the best fallback, not the first: a frame that decoded to the SAME state
            # still says the cell is readable, which "unreadable cell" would deny.
            if fallback is None or (fallback[0] is None and state is not None):
                fallback = (state, text, flag)
            if state is not None and state != against:
                return state, text, flag
            if index == len(frames) - 1:
                break
        return fallback or (None, "", "unreadable")

    for event in events:
        state, text, flag = settled(event["kLast"], prev)
        if state is not None:
            readable += 1
        at = round(offset + event["t"], 2)

        if pending is not None:
            verdict, confirmed = commit_policy(pending, state, last_good)
            if verdict in ("innings", "correction") and confirmed is not None:
                row = {"at": pending_at, "from": last_good.as_dict() if last_good else None,
                       "to": confirmed.as_dict()}
                (innings if verdict == "innings" else corrections).append(row)
                notes.append(f"{verdict} at {pending_at}s: "
                             f"{last_good.text() if last_good else '?'} → {confirmed.text()}")
                # A held read is still a ball that was bowled — the first of the new innings,
                # or the one the scorer went back to fix. Committing it without emitting an
                # event lost five of the eight balls this run missed, including the first ball
                # after the innings change.
                held_delta = (outcome(last_good, confirmed)
                              if last_good is not None and verdict == "correction"
                              and prior_ok(last_good, confirmed) else None)
                held = pending_event or event
                kept.append({"t": pending_at, "kFirst": held["kFirst"], "kLast": held["kLast"],
                             "px": held["px"], "strong": bool(held["strong"]),
                             "score": confirmed.as_dict(), "overs": overs_of(confirmed.balls),
                             "delta": held_delta,
                             # Typed as what it IS, so it never reaches the highlights reel:
                             # a scorer going back to fix a number is not a highlight, and the
                             # state still counts towards ball recall from here.
                             "type": (held_delta or {}).get("t", verdict),
                             "note": f"{verdict}: "
                                     f"{last_good.text() if last_good else '?'} → {confirmed.text()}"})
                prev = confirmed
                last_good = confirmed
            else:
                notes.append(f"dropped an unconfirmed reading at {pending_at}s")
            pending, pending_at, pending_event = None, None, None

        if state is not None and flag == "violation":
            pending, pending_at, pending_event = state, at, event
            continue
        if state is None:
            if event["strong"] and prev is None:
                # Nothing has been read yet, so this is the overlay being DRAWN — team sheets,
                # sponsor cards, the toss line — not a delivery. Given the wicket-long rule it
                # would otherwise open the highlights reel with a minute of graphics apiece.
                setup_noise += 1
            elif event["strong"]:
                kept.append({"t": at, "kFirst": event["kFirst"], "kLast": event["kLast"],
                             "px": event["px"], "strong": True, "score": None, "overs": None,
                             "delta": None, "type": "unknown",
                             "note": f"strong change, unreadable cell ({text!r})"})
            continue
        if prev is not None and state == prev:
            if event["strong"]:
                kept.append({"t": at, "kFirst": event["kFirst"], "kLast": event["kLast"],
                             "px": event["px"], "strong": True, "score": state.as_dict(),
                             "overs": overs_of(state.balls), "delta": None, "type": "unknown",
                             "note": "strong change, the score did not move"})
            prev = state
            last_good = state
            continue
        if prev is None:
            # The moment the scoreboard first became readable. There is no state before it, so
            # there is no ball in it — it is the baseline the rest of the range is measured
            # from. Emitting it as an event gave the highlights reel a minute of pre-match
            # graphics under the wicket-long rule.
            baseline_reads += 1
            prev = state
            last_good = state
            continue
        delta = outcome(prev, state)
        kept.append({"t": at, "kFirst": event["kFirst"], "kLast": event["kLast"],
                     "px": event["px"], "strong": bool(event["strong"]),
                     "score": state.as_dict(), "overs": overs_of(state.balls),
                     "delta": delta, "type": delta["t"],
                     "note": _note_of(prev, state, delta)})
        prev = state
        last_good = state
    if pending is not None:
        notes.append(f"dropped an unconfirmed reading at {pending_at}s (nothing followed it)")
    kept, trailing = _drop_trailing_unknowns(kept)
    before_drop = len(kept)
    kept, dropped = _drop_unknown_runs(kept)
    if setup_noise:
        notes.append(f"dropped {setup_noise} unreadable change(s) before any score had been "
                     "read — the overlay being drawn, not the match")
    if baseline_reads:
        notes.append(f"dropped {baseline_reads} read(s) that first established a score — a "
                     "baseline has nothing before it to differ from, so it is not a delivery")
    if trailing:
        notes.append(f"dropped {trailing} unreadable change(s) after the last readable score "
                     "— the post-match scorecard, not the match")
    if dropped:
        notes.append(f"dropped {dropped} of {before_drop} unreadable change(s) in runs of "
                     f"{UNKNOWN_RUN_DROP}+ — the overlay is absent there, not the match")
    stats = {"readable": readable, "changes": len(events), "keptBeforeRunDrop": before_drop}
    if readable == 0:
        # Nothing in this range ever decoded to a score, so the cell is not a scoreboard — a
        # static scorecard, a drinks break, the wrong crop, or templates from another font. The
        # strong changes above are then just pixels moving, and reporting them as deliveries
        # would be a lie. The CALLER decides between "nothing was happening" and "the cell was
        # changing the whole time and we could not read a word of it", which are different
        # failures with different fixes.
        return [], innings, corrections, notes + [
            f"no readable score anywhere in this range: dropped all {before_drop} change(s) "
            "as noise"], stats
    return kept, innings, corrections, notes, stats


def _drop_trailing_unknowns(kept: list[dict], run: int = UNKNOWN_RUN_DROP) -> tuple[list[dict], int]:
    """Drop a tail of unreadable changes that follows the last score we could read.

    The post-match scorecard redraws itself several times after the cricket has stopped. A tail
    of `run` or more of those is the graphic, not the match — the same judgement as the leading
    guard, at the other end. A shorter tail is left alone: one or two unreadable changes right
    after the last ball could still be the last ball.
    """
    last_read = -1
    for index, event in enumerate(kept):
        if event.get("score") is not None:
            last_read = index
    tail = [e for e in kept[last_read + 1:] if e["type"] == "unknown"]
    if len(tail) < run or len(tail) != len(kept) - last_read - 1:
        return kept, 0
    return kept[:last_read + 1], len(tail)


def _drop_unknown_runs(kept: list[dict], run: int = UNKNOWN_RUN_DROP) -> tuple[list[dict], int]:
    """Drop unreadable events that come in a RUN. One is a glitch worth seeing; a hundred in a
    row is the scoreboard being off the screen, and putting those in a reel gives an operator
    the interval instead of the cricket."""
    out: list[dict] = []
    block: list[dict] = []
    dropped = 0
    for event in kept + [None]:                      # a sentinel flushes the last block
        if event is not None and event["type"] == "unknown":
            block.append(event)
            continue
        if len(block) >= run:
            dropped += len(block)
        else:
            out.extend(block)
        block = []
        if event is not None:
            out.append(event)
    return out, dropped


def _note_of(prev: State | None, cur: State, delta: dict | None) -> str:
    if prev is None or delta is None:
        return cur.text()
    return f"{prev.text()} → {cur.text()}"


# --- audio -----------------------------------------------------------------------------
def audio_envelope(video: str, start: float, end: float,
                   runner: Runner | None = None) -> tuple[np.ndarray, list[str]]:
    """A 10 ms RMS envelope of the FIRST DIFFERENCE of the waveform.

    Differencing is a one-line high-pass: bat on ball is a click, and a click survives it while
    crowd noise and wind do not. No audio, or a decoder that fails, is a note and an empty
    envelope — every window then falls back to the fixed lead.
    """
    args = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}"]
    if end > start:
        args += ["-t", f"{end - start:.3f}"]
    args += ["-i", video, "-vn", "-ac", "1", "-ar", str(AUDIO_RATE), "-f", "s16le", "-"]
    hop = AUDIO_RATE * AUDIO_FRAME_MS // 1000
    rms: list[float] = []
    carry = np.zeros(0, dtype=np.float64)
    last = 0.0
    try:
        # Consumed lazily, one chunk at a time. Ninety minutes of 16 kHz mono is ~175 MB of
        # PCM, and materialising the whole stream before reducing it took peak RSS to 249 MB
        # for a number that only ever needed a 10 ms window.
        chunks = iter([runner(args)]) if runner is not None else _stream(args)
        for chunk in chunks:
            if len(chunk) < 2:
                continue
            samples = np.frombuffer(chunk[:len(chunk) // 2 * 2], dtype="<i2").astype(np.float64) / 32768.0
            diff = np.diff(np.concatenate(([last], samples)))
            last = float(samples[-1])
            buf = np.concatenate((carry, np.abs(diff)))
            usable = len(buf) // hop * hop
            if usable:
                rms.extend(np.sqrt((buf[:usable].reshape(-1, hop) ** 2).mean(axis=1)).tolist())
            carry = buf[usable:]
    except (RuntimeError, OSError) as exc:
        return np.zeros(0, dtype=np.float64), [f"no audio: anchors by lag ({str(exc)[:80]})"]
    env = np.asarray(rms, dtype=np.float64)
    if env.size == 0:
        return env, ["no audio: anchors by lag"]
    return env, []


def _stream(args: Sequence[str], chunk: int = 32000):
    proc = subprocess.Popen(list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    assert proc.stdout is not None
    try:
        while True:
            data = proc.stdout.read(chunk)
            if not data:
                break
            yield data
    finally:
        proc.stdout.close()
        err = proc.stderr.read() if proc.stderr else b""
        if proc.stderr:
            proc.stderr.close()
        if proc.wait() != 0:
            raise RuntimeError(err[-200:].decode(errors="replace") or "ffmpeg failed")


def transients(env: np.ndarray, ratio: float = RATIO,
               min_gap_s: float = MIN_GAP_S) -> list[tuple[float, float]]:
    """[(seconds, strength)] where the envelope jumps clear of its own recent background."""
    if env.size == 0:
        return []
    per_s = 1000 // AUDIO_FRAME_MS
    win = int(AUDIO_BG_S * per_s)
    padded = np.concatenate((np.full(win, env[0]), env))
    cum = np.concatenate(([0.0], np.cumsum(padded)))
    bg = (cum[win:win + env.size] - cum[:env.size]) / max(win, 1)   # causal: the second before
    strength = env / (bg + 1e-9)
    peaks = np.flatnonzero(strength > ratio)
    picked: list[tuple[float, float]] = []
    for index in sorted(peaks, key=lambda i: -strength[i]):
        at = float(index) / per_s
        if all(abs(at - other) >= min_gap_s for other, _s in picked):
            picked.append((round(at, 2), round(float(strength[index]), 2)))
    picked.sort()
    return picked


def event_windows(events: list[dict], peaks: Sequence[tuple[float, float]], offset: float = 0.0,
                  pre: float = PRE_S, post: float = POST_S, lag: float = LAG_S,
                  audio_trim: bool = False,
                  band: tuple[float, float] = AUDIO_TRIM_BAND,
                  trim_pre: float = AUDIO_TRIM_PRE) -> list[dict]:
    """Turn each change into a window that HOLDS the ball, rather than one that guesses at it.

    The window is `[change − pre, change + post]` and nothing about it depends on the audio.
    That is the whole rule, and it is deliberately blunt: the scoreboard is exact about which
    ball and what happened, and vague about when, so the only honest window is one long enough
    to cover the vagueness. Twenty-six seconds back covers every lag in the reference match
    except one entry the scorer made 53 s late.

    THE PREVIOUS VERSION HUNG THE WINDOW ON THE LOUDEST TRANSIENT AND WAS WORSE TO WATCH, which
    is the thing to understand before changing this. A transient search band wide enough to
    find a slow scorer's ball also reaches back into the previous delivery, and when the scorer
    is quick that previous ball is the loudest thing in the band. The clip then opens on a
    batter standing still and ends as the run-up begins. Against the paid run-up times for all
    61 boundaries of this match, counting a clip as good only when it holds the run-up AND the
    shot: this rule 57, the audio-anchored one 45, and a version that trims onto a transient
    inside a band stopping short of the previous ball 50.

    `audio_trim` keeps that last idea available because it is a reasonable thing to want —
    shorter clips — but it is off by default and the docstring above is why.
    """
    back, front = band
    out: list[dict] = []
    for event in events:
        t = float(event["t"])
        start, end = t - pre, t + post
        placement = "overlay"
        if audio_trim:
            window = [(at, strength) for at, strength in peaks
                      if t - back <= at + offset <= t - front]
            if window:
                at = max(window, key=lambda p: p[1])[0] + offset
                start, placement = at - trim_pre, "audio-trimmed"
        row = dict(event)
        row.update({"s": round(max(0.0, start), 2), "e": round(end, 2),
                    "anchor": placement, "anchorAt": round(t - lag, 2),
                    "placement": placement})
        out.append(row)
    return out


# --- the cutter (ported from src/video/match-highlights-cut.ts, argv for argv) ----------
def plan_windows(events: Sequence[dict], duration: float, pre: float = PAD_PRE,
                 post: float = PAD_POST, min_seconds: float = MIN_WINDOW_S,
                 types: Sequence[str] = (), merge_overlaps: bool = True) -> list[dict]:
    """Pad → clamp → drop-short → sort → merge. The proven numbers, not a fresh guess.

    Merging is what stops a burst of events becoming a stutter of near-identical clips, and the
    absorbed notes are appended so the EDL still says what happened. `sources` carries the
    input indices, because un-padding a clamped or merged window cannot recover them.
    """
    keep = {t for t in types if t}
    padded: list[dict] = []
    for index, event in enumerate(events):
        s, e = event.get("s"), event.get("e")
        if not isinstance(s, (int, float)) or not isinstance(e, (int, float)):
            continue
        if not math.isfinite(float(s)) or not math.isfinite(float(e)):
            continue
        if keep and event.get("t") not in keep:
            continue
        start = max(0.0, float(s) - pre)
        end = min(duration, float(e) + post)
        if end - start < min_seconds:
            continue
        padded.append({"start": start, "end": end, "type": event.get("t", "?"),
                       "note": event.get("n", "") or "", "events": 1, "sources": [index]})
    padded.sort(key=lambda w: (w["start"], w["end"]))
    if not merge_overlaps:
        return padded
    merged: list[dict] = []
    for window in padded:
        if merged and window["start"] <= merged[-1]["end"]:
            last = merged[-1]
            last["end"] = max(last["end"], window["end"])
            last["events"] += 1
            last["sources"] = last["sources"] + window["sources"]
            if window["note"]:
                last["note"] = window["note"] if not last["note"] else f"{last['note']} | {window['note']}"
            continue
        merged.append({**window, "sources": list(window["sources"])})
    return merged


def window_seconds(windows: Sequence[dict]) -> float:
    return sum(w["end"] - w["start"] for w in windows)


def build_edl(windows: Sequence[dict]) -> list[dict]:
    return [{"start": round(w["start"], 3), "end": round(w["end"], 3),
             "type": w["type"], "note": w["note"]} for w in windows]


def window_cut_args(source: str, start: float, end: float, output: str) -> list[str]:
    """`-ss` BEFORE `-i` and a re-encode: that is what makes the cut frame-accurate. A stream
    copy would snap every window back to the previous keyframe and lose the run-up."""
    return ["-v", "error", "-ss", f"{start:.3f}", "-i", source, "-t", f"{end - start:.3f}",
            "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p",
            "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-movflags", "+faststart", output]


def build_concat_list(paths: Sequence[str]) -> str:
    return "".join("file '%s'\n" % p.replace("'", "'\\''") for p in paths)


def concat_args(list_path: str, output: str) -> list[str]:
    """Uniform encode params across windows are what let this be a plain `-c copy`."""
    return ["-v", "error", "-f", "concat", "-safe", "0", "-i", list_path,
            "-c", "copy", "-movflags", "+faststart", output]


def filmstrip_grid(seconds: float, interval: int = FILMSTRIP["interval"],
                   columns: int = FILMSTRIP["columns"]) -> dict:
    """`tile=15x-1` is INVALID — tile needs explicit columns AND rows, so the rows are computed
    from how many frames the reel will actually yield. The live run's `-1` produced no strip."""
    columns = max(1, int(columns))
    frames = max(1, math.ceil(seconds / interval))
    return {"frames": frames, "columns": columns, "rows": max(1, math.ceil(frames / columns))}


def filmstrip_args(source: str, output: str, seconds: float,
                   interval: int = FILMSTRIP["interval"], columns: int = FILMSTRIP["columns"],
                   width: int = FILMSTRIP["width"]) -> list[str]:
    grid = filmstrip_grid(seconds, interval, columns)
    return ["-v", "error", "-i", source, "-vf",
            f"fps=1/{interval},scale={width}:-1,tile={grid['columns']}x{grid['rows']}",
            "-frames:v", "1", "-update", "1", output]


def cut_reel(name: str, video: str, windows: Sequence[dict], out_dir: str,
             runner: Runner | None = None) -> dict:
    """Render one reel plus its EDL and filmstrip. A failed filmstrip is a note, never a lost reel."""
    reel = {"name": name, "windows": len(windows), "seconds": round(window_seconds(windows), 2),
            "path": None, "edl": None, "filmstrip": None, "notes": []}
    edl_path = os.path.join(out_dir, f"{name}.edl.json")
    with open(edl_path, "w", encoding="utf-8") as fh:
        json.dump(build_edl(windows), fh, indent=1)
    reel["edl"] = edl_path
    if not windows:
        reel["notes"].append("no windows: reel skipped")
        return reel
    output = os.path.join(out_dir, f"{name}.mp4")
    tmp = tempfile.mkdtemp(prefix=f"mhl-{name}-")
    parts: list[str] = []
    for index, window in enumerate(windows):
        part = os.path.join(tmp, f"w{index:04d}.mp4")
        try:
            run([FFMPEG, "-y"] + window_cut_args(video, window["start"], window["end"], part), runner)
        except RuntimeError as exc:
            reel["notes"].append(f"window {index} failed: {str(exc)[:120]}")
            continue
        parts.append(part)
    if not parts:
        reel["notes"].append("every window failed to cut: reel skipped")
        return reel
    list_path = os.path.join(tmp, "concat.txt")
    with open(list_path, "w", encoding="utf-8") as fh:
        fh.write(build_concat_list(parts))
    try:
        run([FFMPEG, "-y"] + concat_args(list_path, output), runner)
        reel["path"] = output
    except RuntimeError as exc:
        reel["notes"].append(f"concat failed: {str(exc)[:120]}")
        return reel
    strip = os.path.join(out_dir, f"{name}.strip.jpg")
    try:
        run([FFMPEG, "-y"] + filmstrip_args(output, strip, reel["seconds"]), runner)
        reel["filmstrip"] = strip
    except RuntimeError as exc:
        reel["notes"].append(f"filmstrip failed: {str(exc)[:120]}")
    return reel


# --- eval ------------------------------------------------------------------------------
def dedupe(times: Sequence[float], within: float = EVAL_DEDUPE_S) -> list[float]:
    """Ground truth lists the same ball more than once; two entries this close are one ball."""
    out: list[float] = []
    for at in sorted(float(t) for t in times):
        if not out or at - out[-1] > within:
            out.append(at)
    return out


def ball_recall(events: Sequence[dict], scores: Sequence[object]) -> dict:
    """Did we reach every state the overlay itself passed through? A time-free recall.

    This is the honest denominator. The verified delivery list carries roughly eighty duplicate
    entries across the match, so scoring against its length reads as a miss rate that is really
    a double-count; the overlay's own sequence of scores does not have that problem. A label
    transition that advanced the match is one real ball, and it counts as found when our reading
    reached the same runs/wickets/balls.
    """
    states = []
    for row in scores:
        text = _label_text(row)
        states.append(parse_state(text) if text else None)
    ours = {(e["score"]["runs"], e["score"]["wkts"], e["score"]["balls"])
            for e in events if isinstance(e.get("score"), dict)}
    real = found = breaks = skipped = 0
    prev: State | None = None
    for state in states:
        if state is None:
            continue
        if prev is None:
            prev = state
            continue
        if not prior_ok(prev, state):
            breaks += 1                      # an innings change or a scorer's correction
            prev = state
            continue
        if state.balls > prev.balls or state.runs > prev.runs or state.wkts > prev.wkts:
            real += 1
            skipped += max(0, (state.balls - prev.balls) - 1)
            if (state.runs, state.wkts, state.balls) in ours:
                found += 1
        prev = state
    return {"realBalls": real, "found": found,
            "recall": round(found / real, 4) if real else 0.0,
            "ballsTheLabelsSkipped": skipped, "labelBreaks": breaks}


def _typed_by_state(detections: Sequence[dict], truth: Sequence[dict],
                    boundaries: Sequence[dict], scores: Sequence[object],
                    max_gap: float = EVAL_TOLERANCE_S + 2 * LAG_S) -> dict:
    """Boundary typing with no clock in it at all.

    Both the verified boundary time and our own anchor are estimates of when a ball was
    bowled, so comparing them measures two kinds of timing error on top of the typing. This
    does not: the boundary is mapped to its delivery, the labels either side of that delivery
    give the score the ball ended on, and the question becomes whether OUR event that reached
    that same score called it the same thing.

    It assumes the delivery list and the label rows are index-aligned, which they are when
    both come from one run over the same footage. A label row is the score BEFORE its
    delivery — the crops are grabbed a second ahead of the ball — so the state a boundary
    ends on is the NEXT row.

    The pairing is BOUNDED by `max_gap`. Without a bound a score can be claimed by an event two
    minutes away, which is not evidence of anything; the bound is the tolerance plus twice the
    scorer's fallback lead, which covers the whole measured spread and nothing beyond it. A
    score that three or more boundaries all map to is reported in `ambiguousStates` rather than
    credited, because the index alignment has clearly slipped there.
    """
    def label(index: int) -> State | None:
        row = scores[index] if 0 <= index < len(scores) else None
        text = _label_text(row)
        return parse_state(text) if text else None

    ours = {(e["score"]["runs"], e["score"]["wkts"], e["score"]["balls"]): e
            for e in detections if isinstance(e.get("score"), dict)}
    out: dict = {"events": 0, "correct": 0, "maxGap": round(max_gap, 1), "confusion": {},
                 "unmatchedStates": [], "ambiguousStates": []}
    times = [float(row.get("s", 0.0)) for row in truth]
    claims: dict[tuple[int, int, int], list[float]] = {}
    for row in boundaries:
        at = float(row.get("s", 0.0))
        if not times:
            continue
        state = label(min(range(len(times)), key=lambda k: abs(times[k] - at)) + 1)
        if state is not None:
            claims.setdefault((state.runs, state.wkts, state.balls), []).append(at)
    for row in boundaries:
        kind = row.get("kind")
        at = float(row.get("s", 0.0))
        out["events"] += 1
        if not times:
            continue
        index = min(range(len(times)), key=lambda k: abs(times[k] - at))
        state = label(index + 1)
        if state is None:
            got = "no-label"
        else:
            key = (state.runs, state.wkts, state.balls)
            event = ours.get(key)
            if len(claims.get(key, ())) >= 3:
                got = "ambiguous"
                out["ambiguousStates"].append({"at": at, "kind": kind, "score": state.text(),
                                               "claimedBy": len(claims[key])})
            elif event is None:
                got = "state-not-detected"
                out["unmatchedStates"].append({"at": at, "kind": kind, "score": state.text()})
            elif abs(float(event.get("anchorAt", event.get("t", 0.0))) - at) > max_gap:
                got = "state-too-far"
                out["unmatchedStates"].append({
                    "at": at, "kind": kind, "score": state.text(),
                    "gap": round(float(event.get("anchorAt", event.get("t", 0.0))) - at, 1)})
            else:
                got = event["type"]
        if got == kind:
            out["correct"] += 1
        label_key = f"{kind}->{got}"
        out["confusion"][label_key] = out["confusion"].get(label_key, 0) + 1
    out["unmatchedStates"] = out["unmatchedStates"][:20]
    out["ambiguousStates"] = out["ambiguousStates"][:20]
    return out


def contains_shot(windows: Sequence[dict], boundaries: Sequence[dict],
                  lead: float = SHOT_LEAD_S, shot: float = SHOT_END_S) -> dict:
    """Does the clip actually SHOW the ball — the run-up and the shot, not just the moment?

    This replaces an earlier measure that asked whether the ball's timestamp fell anywhere
    inside a padded window. It scored 56 of 61 while the reels were visibly wrong, because a
    clip can hold a timestamp and still open on a batter standing still and end as the run-up
    begins. Here a boundary counts only when the rendered window holds BOTH `lead` seconds and
    `shot` seconds after the run-up starts — which is to say, the viewer sees the delivery and
    what came of it.

    The run-up time is the boundary row's own `s`, which is what the verified reels record;
    on the reference match it is identical to the paid EDL's `start + 1.0` for all 61 rows.
    Pads are included, because the padded window is what gets written.
    """
    out = {"events": 0, "shown": 0, "windows": len(windows),
           "seconds": round(window_seconds(windows), 1),
           "meanClipSeconds": round(window_seconds(windows) / len(windows), 1) if windows else 0.0,
           "notShown": []}
    for row in boundaries:
        kind = row.get("kind")
        runup = float(row.get("s", 0.0))
        out["events"] += 1
        holding = [w for w in windows
                   if w["start"] <= runup + lead and runup + shot <= w["end"]]
        if holding:
            out["shown"] += 1
            continue
        nearest = min(windows, key=lambda w: min(abs(w["start"] - runup), abs(w["end"] - runup)),
                      default=None)
        out["notShown"].append({
            "runUp": round(runup, 1), "kind": kind,
            "nearest": ([round(nearest["start"], 1), round(nearest["end"], 1)] if nearest else None),
            "nearestType": nearest["type"] if nearest else None,
            "why": ("clip opens after the run-up" if nearest and nearest["start"] > runup + lead
                    else "clip ends before the shot" if nearest else "no clip near it")})
    out["notShown"] = out["notShown"][:20]
    return out


def evaluate(events: Sequence[dict], truth: Sequence[dict], boundaries: Sequence[dict],
             scores: Sequence[object] = (), tolerance: float = EVAL_TOLERANCE_S,
             lag: float = LAG_S, reels: dict[str, Sequence[dict]] | None = None) -> dict:
    """Detections against the verified reels: recall, timing, and what was typed wrong.

    Matching is on the ESTIMATED ACTION TIME, never on the scoreboard change. The scorer types
    5.5–16 s after the ball, so a tolerance centred on the change would be comparing against a
    clock that is deliberately late and would miss almost everything.

    An unmatched detection is reported WITH its decoded delta, because ground truth has known
    skips: a detection whose overlay delta is `balls +1` is a ball the list missed, not a false
    positive, and calling it one would hide the detector's real precision.
    """
    gt = dedupe([row.get("s", 0.0) for row in truth])
    detections = sorted(events, key=lambda e: e.get("anchorAt", e.get("t", 0.0)))
    used: set[int] = set()
    matched: list[tuple[float, dict]] = []
    for at in gt:
        best_index, best_gap = -1, tolerance + 1.0
        for index, event in enumerate(detections):
            if index in used:
                continue
            gap = abs(float(event.get("anchorAt", event.get("t", 0.0))) - at)
            if gap < best_gap:
                best_index, best_gap = index, gap
        if best_index >= 0 and best_gap <= tolerance:
            used.add(best_index)
            matched.append((at, detections[best_index]))
    unmatched = [{"change": e.get("t"), "anchorAt": e.get("anchorAt"), "type": e.get("type"),
                  "delta": e.get("delta"), "note": e.get("note")}
                 for i, e in enumerate(detections) if i not in used]

    def stats(rows: Sequence[float]) -> dict:
        if not rows:
            return {"n": 0, "median": None, "p90": None}
        arr = np.sort(np.asarray(rows, dtype=np.float64))
        return {"n": len(arr), "median": round(float(np.median(arr)), 2),
                "p90": round(float(arr[min(len(arr) - 1, int(0.9 * len(arr)))]), 2)}

    by_anchor: dict[str, dict] = {}
    for kind in ("audio", "lag"):
        ds = [float(ev.get("s", 0.0)) - at for at, ev in matched if ev.get("anchor") == kind]
        de = [float(ev.get("e", 0.0)) - at for at, ev in matched if ev.get("anchor") == kind]
        by_anchor[kind] = {"deltaStart": stats(ds), "deltaEnd": stats(de)}

    # THE BAR IS `contains`: did a clip we would cut actually hold the ball, and did we call
    # that clip the right thing. It is the only one of these numbers a viewer can feel. The
    # window used is the event's own, BEFORE the cutter's padding, so the bar measures the
    # placement rule rather than the generosity of the pad.
    #
    # `withinAssociation` stays beside it as a diagnostic: the nearest detection inside
    # tolerance + lag. Both estimates of when a ball was bowled carry error — the measured
    # spread between them is a median of 4.5 s — so a pairing measure says as much about the
    # two clocks as about the reading.
    window = tolerance + lag
    typed = {"events": 0, "contains": 0, "withinAssociation": 0,
             "tolerance": round(tolerance, 1), "associationWindow": round(window, 1),
             "confusion": {}, "associationConfusion": {}, "notInAnyClip": []}
    for row in boundaries:
        kind = row.get("kind")
        at = float(row.get("s", 0.0))
        gap_of = lambda ev: abs(float(ev.get("anchorAt", ev.get("t", 0.0))) - at)  # noqa: E731
        typed["events"] += 1

        near = sorted((ev for ev in detections if gap_of(ev) <= window), key=gap_of)
        paired = near[0] if near else None
        if paired is None:
            held = "missed"
        elif not (float(paired.get("s", 0.0)) <= at <= float(paired.get("e", 0.0))):
            held = "outside-the-clip"
            typed["notInAnyClip"].append({
                "at": at, "kind": kind, "type": paired.get("type"),
                "clip": [paired.get("s"), paired.get("e")],
                "outsideBy": round(max(float(paired.get("s", 0.0)) - at,
                                       at - float(paired.get("e", 0.0))), 1)})
        else:
            held = paired.get("type")
        if held == kind:
            typed["contains"] += 1
        typed["confusion"][f"{kind}->{held}"] = typed["confusion"].get(f"{kind}->{held}", 0) + 1

        got = near[0].get("type") if near else "missed"
        if got == kind:
            typed["withinAssociation"] += 1
        key = f"{kind}->{got}"
        typed["associationConfusion"][key] = typed["associationConfusion"].get(key, 0) + 1
    typed["notInAnyClip"] = typed["notInAnyClip"][:20]
    if scores and truth:
        typed["byState"] = _typed_by_state(detections, truth, boundaries, scores,
                                           tolerance + 2 * lag)
    shots = {name: contains_shot(windows, boundaries)
             for name, windows in (reels or {}).items()}
    recall = len(matched) / len(gt) if gt else 0.0
    report = {"groundTruth": len(truth), "groundTruthDeduped": len(gt),
              "detections": len(detections), "matched": len(matched), "recall": round(recall, 4),
              "precision": round(len(matched) / len(detections), 4) if detections else 0.0,
              "unmatched": unmatched[:40], "unmatchedCount": len(unmatched),
              "timingByAnchor": by_anchor, "typed": typed, "containsShot": shots}
    if scores:
        report["balls"] = ball_recall(events, scores)
    return report


# --- template building -----------------------------------------------------------------
BUILD_CELL = (16, 50, 455, 610)          # the read cell inside a 900×70 `crop=900:70:190:635` band


def _crop_cell(path: str) -> np.ndarray:
    from PIL import Image
    top, bottom, left, right = BUILD_CELL
    return np.asarray(Image.open(path).convert("L"))[top:bottom, left:right]


def _label_text(row: object) -> str | None:
    if not isinstance(row, dict) or row.get("runs") is None:
        return None
    overs = str(row.get("overs", ""))
    if "." in overs and (not overs.split(".")[-1].isdigit() or int(overs.split(".")[-1]) > 5):
        return None
    text = f"{row.get('runs')}/{row.get('wkts')} ({overs})"
    return text if parse_state(text) else None


def collect_labelled(pairs: Sequence[tuple[str, str]]) -> list[tuple[str, str]]:
    """[(crop dir, labels json)] → [(crop path, label text)], filtered.

    Rows the labeller could not read, impossible ball digits, and rows that contradict BOTH
    their neighbours are dropped before anything is averaged: a template built from a wrong
    label is a wrong template forever.
    """
    out: list[tuple[str, str]] = []
    for crop_dir, labels_path in pairs:
        with open(labels_path, encoding="utf-8") as fh:
            scores = (json.load(fh) or {}).get("scores") or []
        texts = [_label_text(row) for row in scores]
        states = [parse_state(t) if t else None for t in texts]
        for index, text in enumerate(texts):
            if text is None or states[index] is None:
                continue
            prev = states[index - 1] if index > 0 else None
            nxt = states[index + 1] if index + 1 < len(states) else None
            ok_prev = prev is None or prior_ok(prev, states[index])
            ok_next = nxt is None or prior_ok(states[index], nxt)
            if not ok_prev and not ok_next:
                continue
            path = os.path.join(crop_dir, f"d{index:03d}.png")
            if os.path.isfile(path):
                out.append((path, text))
    return out


def build_templates(pairs: Sequence[tuple[str, str]]) -> tuple[dict, dict]:
    """Two passes over the labelled crops → (template document, report).

    Pass one uses plain column splitting and keeps only the crops where the glyph count already
    matches the label, which is enough to seed every class. Pass two re-segments with those
    templates — merged digits now separate — and rebuilds from every crop that reads back
    correctly, so the averages come from three times as many samples.
    """
    from overlay_read import binarise, bucket_of, contiguous_gap, segment

    items = [(path, text, parse_state(text)) for path, text in collect_labelled(pairs)]
    report: dict = {"labelled": len(items)}

    def samples(templates: dict | None) -> tuple[list, int]:
        rows, used = [], 0
        for path, text, _state in items:
            mask = binarise(_crop_cell(path))
            glyphs = sorted(segment(mask, templates), key=lambda g: g.x0)
            large = [g for g in glyphs if bucket_of(g.h) == "L"]
            small = [g for g in glyphs if bucket_of(g.h) == "S"]
            if not large:
                continue
            gap = contiguous_gap([(g.x0, g.x1, g.y0, g.y1) for g in large])
            runs: list[list] = []
            for g in large:
                if runs and g.x0 - runs[-1][-1].x1 <= gap:
                    runs[-1].append(g)
                else:
                    runs.append([g])
            run = max(runs, key=len)
            right = run[-1].x1
            overs = [g for g in small if g.x0 >= right]
            want_score, want_overs = text.split(" ")[0], text.split(" ")[1]
            if len(run) != len(want_score) or len(overs) != len(want_overs):
                continue
            used += 1
            for glyph, char in list(zip(run, want_score)) + list(zip(overs, want_overs)):
                rows.append((glyph.bucket, char, mask[glyph.y0:glyph.y1, glyph.x0:glyph.x1],
                             glyph.w, glyph.h))
        return rows, used

    def readback(templates: dict) -> tuple[int, dict]:
        exact, confusion = 0, {}
        prev: State | None = None
        for path, text, _state in items:
            read = parse_cell(_crop_cell(path), templates)
            state, got, flag = decode(read, prev)
            if got == text:
                exact += 1
            else:
                confusion[f"{text} -> {got}"] = confusion.get(f"{text} -> {got}", 0) + 1
            if state is not None and not flag:
                prev = state
        return exact, confusion

    total = max(len(items), 1)
    rows1, used1 = samples(None)
    doc1 = templates_from_labels(rows1)
    live1 = hydrate_templates(doc1)
    exact1, confusion1 = readback(live1)
    rows2, used2 = samples(live1)
    doc2 = templates_from_labels(rows2) if rows2 else doc1
    live2 = hydrate_templates(doc2)
    exact2, confusion2 = readback(live2)

    # Pass two sees three times as many crops — merged digits separate once there are templates
    # to split them against — so it should generalise better to live frames than pass one does.
    # But "should" is not "does", so it is CHOSEN, not assumed: it is kept unless it reads back
    # more than TEMPLATE_PASS_TOLERANCE worse than pass one on the same crops.
    keep_two = (exact2 / total) >= (exact1 / total) - TEMPLATE_PASS_TOLERANCE
    doc, confusion, chosen = ((doc2, confusion2, "pass2") if keep_two
                              else (doc1, confusion1, "pass1"))
    report.update({
        "pass1": {"crops": used1, "glyphs": len(rows1),
                  "readBack": exact1, "accuracy": round(exact1 / total, 4)},
        "pass2": {"crops": used2, "glyphs": len(rows2),
                  "readBack": exact2, "accuracy": round(exact2 / total, 4)},
        "chosen": chosen, "passTolerance": TEMPLATE_PASS_TOLERANCE,
        "counts": doc.get("counts", {}), "widths": doc.get("widths", {}),
        "confusion": dict(sorted(confusion.items(), key=lambda kv: -kv[1])[:20]),
    })
    return doc, report


# --- CLI -------------------------------------------------------------------------------
def parse_cell_arg(text: str) -> tuple[int, int, int, int]:
    parts = [p.strip() for p in str(text).split(",")]
    if len(parts) != 4 or not all(p.lstrip("-").isdigit() for p in parts):
        raise ValueError("--cell wants four integers: x,y,w,h")
    x, y, w, h = (int(p) for p in parts)
    if w <= 0 or h <= 0 or x < 0 or y < 0:
        raise ValueError("--cell wants a positive box inside the frame")
    return x, y, w, h


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--video", default="")
    ap.add_argument("--out", default="", help="directory for the reels, EDLs and the artifact")
    ap.add_argument("--cell", default="", help="x,y,w,h of the score cell (default: detected)")
    ap.add_argument("--templates", default=DEFAULT_TEMPLATES)
    ap.add_argument("--start", type=float, default=0.0)
    ap.add_argument("--end", type=float, default=0.0, help="default: the whole video")
    ap.add_argument("--pre", type=float, default=PRE_S,
                    help="seconds before the overlay change the clip opens (the scorer's lag "
                         "lives in here, so it is long on purpose)")
    ap.add_argument("--post", type=float, default=POST_S,
                    help="seconds after the overlay change the clip closes")
    ap.add_argument("--lag", type=float, default=LAG_S, help="fallback lead before the change")
    ap.add_argument("--audio-trim", action="store_true",
                    help="OPT-IN: let a transient just before the change pull the window start "
                         "forward. Shorter clips, but measured worse on the reference match "
                         "(50 of 61 boundaries hold the run-up and the shot, against 57 without)")
    ap.add_argument("--pad-pre", type=float, default=PAD_PRE)
    ap.add_argument("--pad-post", type=float, default=PAD_POST)
    ap.add_argument("--min", dest="min_seconds", type=float, default=MIN_WINDOW_S)
    ap.add_argument("--types", default=",".join(DEFAULT_TYPES), help="types in the highlights reel")
    ap.add_argument("--dry-run", action="store_true", help="plan only; writes nothing")
    ap.add_argument("--eval", dest="eval_path", default="", help="a verified.json to score against")
    ap.add_argument("--eval-boundaries", default="", help="a boundaries-final.json for the typing matrix")
    ap.add_argument("--tolerance", type=float, default=EVAL_TOLERANCE_S)
    ap.add_argument("--min-recall", type=float, default=EVAL_MIN_RECALL,
                    help="the --eval ball-recall bar")
    ap.add_argument("--min-contains-shot", type=float, default=EVAL_MIN_CONTAINS_SHOT,
                    help="the --eval bar: the fraction of boundaries whose rendered clip shows "
                         "the run-up AND the shot")
    ap.add_argument("--min-typed", type=float, default=None,
                    help="OPT-IN: also require this ratio of boundaries to be typed correctly "
                         "in the clip that holds them (no default; see SKILL.md)")
    ap.add_argument("--build-templates", nargs=2, action="append", metavar=("CROPS", "LABELS"),
                    default=None, help="repeatable; writes --templates and exits")
    args = ap.parse_args()

    if args.build_templates:
        for crops, labels in args.build_templates:
            if not os.path.isdir(crops):
                say(f"no crop directory at {crops}"); raise SystemExit(2)
            if not os.path.isfile(labels):
                say(f"no labels file at {labels}"); raise SystemExit(2)
        doc, report = build_templates([(c, l) for c, l in args.build_templates])
        os.makedirs(os.path.dirname(os.path.abspath(args.templates)) or ".", exist_ok=True)
        with open(args.templates, "w", encoding="utf-8") as fh:
            json.dump(doc, fh, separators=(",", ":"), sort_keys=True)
        say(f"wrote {args.templates}")
        print(json.dumps({"kind": "match-highlights-local-templates", "path": args.templates,
                          **report}, indent=1))
        return

    if not args.video or not os.path.isfile(args.video):
        say(f"no video at {args.video!r}"); raise SystemExit(2)
    if not args.out and not args.dry_run:
        say("--out is required (or --dry-run)"); raise SystemExit(2)
    if not os.path.isfile(args.templates):
        say(f"no templates at {args.templates} — build them with --build-templates"); raise SystemExit(2)
    if args.eval_path and not args.eval_boundaries:
        say("--eval needs --eval-boundaries too: without the label rows there is no ball count "
            "to measure recall against and no boundary list to measure typing against, and the "
            "delivery list on its own double-counts by about one ball in six")
        raise SystemExit(2)
    try:
        templates = load_templates(args.templates)
    except (OSError, ValueError) as exc:
        say(f"unreadable templates at {args.templates}: {exc}"); raise SystemExit(2) from None
    override = None
    if args.cell:
        try:
            override = parse_cell_arg(args.cell)
        except ValueError as exc:
            say(str(exc)); raise SystemExit(2) from None

    truth: list[dict] = []
    boundaries: list[dict] = []
    label_scores: list[object] = []
    if args.eval_path:
        # Read and check the evaluation inputs BEFORE the video is opened. They cost nothing to
        # validate and everything to get wrong: an empty list here used to reach the gate as a
        # pass over nothing at all, because recall quietly fell back to the duplicated delivery
        # list and coverage and typing were skipped for want of rows to measure.
        try:
            with open(args.eval_path, encoding="utf-8") as fh:
                truth = (json.load(fh) or {}).get("deliveries") or []
        except (OSError, ValueError) as exc:
            say(f"unreadable --eval file: {exc}"); raise SystemExit(2) from None
        if not truth:
            say(f"{os.path.basename(args.eval_path)} lists no deliveries — nothing to score")
            raise SystemExit(2)
        try:
            with open(args.eval_boundaries, encoding="utf-8") as fh:
                loaded = json.load(fh) or {}
        except (OSError, ValueError) as exc:
            say(f"unreadable --eval-boundaries file: {exc}"); raise SystemExit(2) from None
        boundaries = loaded.get("boundaries") or []
        label_scores = loaded.get("scores") or []
        if not boundaries or not label_scores:
            say(f"{os.path.basename(args.eval_boundaries)} carries {len(boundaries)} boundary "
                f"row(s) and {len(label_scores)} score row(s) — both are needed: the score rows "
                "are the ball count recall is measured against, the boundary rows are what "
                "coverage and typing are measured on")
            raise SystemExit(2)

    notes: list[str] = []
    try:
        info = probe(args.video)
    except (RuntimeError, ValueError) as exc:
        say(f"ffprobe could not read {os.path.basename(args.video)}: {str(exc)[:200]}")
        raise SystemExit(2) from None
    if info["width"] <= 0 or info["height"] <= 0:
        say(f"{os.path.basename(args.video)} has no video stream"); raise SystemExit(2)
    duration = info["duration"]
    start = max(0.0, args.start)
    end = args.end if args.end > 0 else duration
    say(f"{os.path.basename(args.video)} {info['width']}×{info['height']} {duration:.0f}s "
        f"— reading {start:.0f}-{end:.0f}s")

    overlay = detect_overlay(args.video, info)
    notes += overlay.pop("notes", [])
    if override is not None:
        overlay["cell"] = list(override)
        overlay["override"] = True
        notes.append(f"--cell overrode the detected box: {override}")
    cell = overlay["cell"]
    say(f"cell {cell} (detected: {overlay['detected']})")

    frames = sample_cell(args.video, cell, start, end)
    say(f"{len(frames)} frames sampled")
    raw_events = change_events(frames)
    say(f"{len(raw_events)} raw changes")
    if not overlay["detected"] and override is None and not raw_events:
        say("no overlay detected and the cell never changes — nothing to read here")
        print(json.dumps({"kind": "match-highlights-local", "source": os.path.abspath(args.video),
                          "overlay": overlay, "events": [], "providerCalls": 0,
                          "notes": notes + ["refused: no overlay and no change"]}, indent=1))
        raise SystemExit(4)

    events, innings, corrections, read_notes, read_stats = read_states(
        frames, raw_events, templates, start)
    notes += read_notes
    say(f"{len(events)} deliveries read")
    span = max(end - start, 1.0)
    busy = (len(raw_events) >= REFUSE_MIN_CHANGES
            and len(raw_events) / span >= 1.0 / REFUSE_MIN_RATE_S)
    if busy and read_stats["readable"] == 0:
        say(f"the cell changed {len(raw_events)} time(s) in {span:.0f}s and never decoded — "
            "these templates are not this overlay's font. Rebuild them with "
            "--build-templates, or point --cell at the right box.")
        print(json.dumps({"kind": "match-highlights-local", "source": os.path.abspath(args.video),
                          "overlay": overlay, "events": [], "providerCalls": 0,
                          "readStats": read_stats,
                          "notes": notes + ["refused: the cell changes but never decodes"]},
                         indent=1))
        raise SystemExit(4)

    peaks: list[tuple[float, float]] = []
    if args.audio_trim:
        env, audio_notes = audio_envelope(args.video, start, end)
        notes += audio_notes
        peaks = transients(env)
        say(f"{len(peaks)} audio transients")
    else:
        # The default window does not use the audio at all, so the whole decode pass is
        # skipped: about a minute per 91-minute part, for a number nothing reads.
        notes.append("clips are anchored on the overlay; the audio pass was skipped "
                     "(--audio-trim opts into it)")

    windowed = event_windows(events, peaks, start, pre=args.pre, post=args.post, lag=args.lag,
                             audio_trim=args.audio_trim)
    types = tuple(t.strip() for t in args.types.split(",") if t.strip())
    reel_plans = {
        "all-events": plan_windows([_w(e) for e in windowed], duration, args.pad_pre,
                                   args.pad_post, args.min_seconds),
        "highlights": plan_windows([_w(e) for e in windowed], duration, args.pad_pre,
                                   args.pad_post, args.min_seconds, types=types),
    }
    by_type: dict[str, int] = {}
    for event in windowed:
        by_type[event["type"]] = by_type.get(event["type"], 0) + 1
    by_placement: dict[str, int] = {}
    for event in windowed:
        by_placement[event["placement"]] = by_placement.get(event["placement"], 0) + 1
    counts = {"deliveries": len(windowed), "byType": by_type, "byPlacement": by_placement,
              "anchoredByAudio": sum(1 for e in windowed if e["anchor"] == "audio")}

    doc = {
        "schemaVersion": 1, "kind": "match-highlights-local",
        "source": os.path.abspath(args.video), "generatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "sport": "cricket", "model": "none", "overlay": overlay, "sampleFps": 1,
        "range": {"start": round(start, 2), "end": round(end, 2), "duration": round(duration, 2)},
        "events": [{"s": e["s"], "e": e["e"], "t": e["type"], "n": e["note"],
                    "score": e["score"], "overs": e["overs"], "change": round(e["t"], 2),
                    "anchor": e["anchor"], "anchorAt": e["anchorAt"],
                    "placement": e["placement"], "delta": e["delta"]}
                   for e in windowed],
        "innings": innings, "corrections": corrections, "reels": [],
        "counts": counts, "providerCalls": 0, "notes": notes,
    }

    if args.eval_path:
        report = evaluate([{**e, "t": e["change"], "type": e["t"]} for e in doc["events"]],
                          truth, boundaries, label_scores, args.tolerance, args.lag,
                          reels=reel_plans)
        doc["eval"] = report
        balls = report.get("balls")
        typed = report["typed"]
        by_state = typed.get("byState") or {}
        hl = (report.get("containsShot") or {}).get("highlights") or {}
        allev = (report.get("containsShot") or {}).get("all-events") or {}
        if balls:
            say(f"balls {balls['recall']:.1%} ({balls['found']}/{balls['realBalls']})")
        if hl:
            say(f"highlights reel SHOWS the ball in {hl['shown']}/{hl['events']} "
                f"({hl['shown'] / max(hl['events'], 1):.1%}), mean clip {hl['meanClipSeconds']}s"
                + (f" · all-events {allev['shown']}/{allev['events']}" if allev else ""))
        say(f"placement {typed['contains']}/{typed['events']} contains · "
            f"{typed['withinAssociation']}/{typed['events']} at {typed['associationWindow']:.0f}s"
            + (f" · {by_state['correct']}/{by_state['events']} by state" if by_state else "")
            + f" · listed recall {report['recall']:.1%}")

    if args.dry_run:
        doc["dryRun"] = True
        doc["plannedWindows"] = {name: {"windows": len(w), "seconds": round(window_seconds(w), 2)}
                                 for name, w in reel_plans.items()}
        print(json.dumps(doc, indent=1))
        _eval_gate(doc, args.min_recall, args.min_contains_shot, args.min_typed)
        return

    os.makedirs(args.out, exist_ok=True)
    for name, windows in reel_plans.items():
        say(f"cutting {name}: {len(windows)} windows, {window_seconds(windows):.0f}s")
        doc["reels"].append(cut_reel(name, args.video, windows, args.out))
    artifact = os.path.join(args.out, "match-highlights-local.json")
    with open(artifact, "w", encoding="utf-8") as fh:
        json.dump(doc, fh, indent=1)
    doc["artifact"] = artifact
    print(json.dumps(doc, indent=1))
    say(f"wrote {artifact}")
    _eval_gate(doc, args.min_recall, args.min_contains_shot, args.min_typed)


def _w(event: dict) -> dict:
    return {"s": event["s"], "e": event["e"], "t": event["type"], "n": event["note"]}


def _eval_gate(doc: dict, min_recall: float, min_contains_shot: float,
               min_typed: float | None) -> None:
    """BOTH bars, and the message names the one that failed.

    Recall on its own passed a run that typed nothing at all: every ball found, every one of
    them called a dot, exit 0. Recall says the detector saw the match; typing says it
    understood it, and a highlights reel needs both.

    The two bars are what the method actually guarantees. Recall says the detector saw every
    ball, measured against the overlay's own ball count — the verified delivery list
    double-counts and would fail a clean run. `containsShot` says the rendered clip SHOWS it:
    the run-up and the shot both inside the window that gets written. The bar it replaced asked
    only whether the ball's timestamp fell somewhere inside a padded window, and scored 56 of 61
    on reels that opened on a batter standing still and ended as the run-up began.

    Typing is NOT a default bar. On this footage the reading is near-perfect and what limits
    the typed numbers is the scorer's lag, which is a property of the broadcast rather than of
    the reader; a default that fails on a correct run teaches people to pass `--min-typed 0`.
    Pass `--min-typed` to enforce it on `contains` when the footage warrants it.
    """
    report = doc.get("eval")
    if not report:
        return
    balls = report.get("balls")
    recall = balls["recall"] if balls else report["recall"]
    failed: list[str] = []
    if recall < min_recall:
        failed.append(f"recall {recall:.1%} < {min_recall:.0%}")
    highlights = (report.get("containsShot") or {}).get("highlights") or {}
    if highlights.get("events"):
        ratio = highlights["shown"] / highlights["events"]
        if ratio < min_contains_shot:
            failed.append(f"the highlights reel shows the ball in {highlights['shown']}/"
                          f"{highlights['events']} ({ratio:.1%}) < {min_contains_shot:.0%}")
    typed = report.get("typed") or {}
    events = typed.get("events") or 0
    if min_typed is not None and events:
        correct = typed.get("contains", 0)
        if correct / events < min_typed:
            failed.append(f"typed {correct}/{events} ({correct / events:.1%}, the clip holds "
                          f"the ball) < {min_typed:.1%}")
    if failed:
        say("the --eval bar was not met: " + "; ".join(failed))
        raise SystemExit(4)


if __name__ == "__main__":
    main()
