#!/usr/bin/env python3
"""overlay_read.py — read a broadcast score cell with numpy + Pillow. No network, no subprocess.

The one idea: a cricket scoreboard overlay already carries the whole match. The overs counter
ticks once per legal ball and the total says what the ball scored, so turning six hours of
footage into its boundaries needs no video understanding at all — only the twelve glyphs of
`R/W (O.B)`.

This module is the reading half and is PURE: given a grayscale cell it returns a `Read`, and
given a previous `State` it decodes the most plausible new state. It never opens a video,
never spawns a process and never touches the network. `scoreboard_highlights.py` is the half
that runs ffmpeg.

Pipeline per cell:

  binarise    gray < INK is ink; a row that is almost all ink is a border line, blanked.
  components  split on empty columns → one box per connected run of columns.
  segment     a component wider than one glyph is SPLIT by dynamic programming against the
              templates' own native widths. Measured on 544 labelled crops of the 2026-09-16
              match: plain column splitting gets the large digits right 89.9% of the time and
              the small overs digits 62.1%, and EVERY error is a merge — glyphs fuse, they
              never fragment. So the splitter, not a different ink threshold, is the fix.
  classify    '.', '(' and ')' by geometry alone (a 2×2 dot resized to 12×20 is a filled block
              indistinguishable from a resized '1'); digits and '/' by template cost.
  parse_cell  the anchor rule: the contiguous run of large glyphs containing '/' is `R/W`;
              small glyphs between '(' and ')' to its right are the overs; anything to the
              left (the team-name tail that shares the cell) is discarded.
  decode      the lowest-cost candidate that satisfies the monotonic prior against the
              previous state. Runs never decrease, a ball is one delivery, the ball digit is
              at most 5.
  commit_policy   a read that violates the prior is HELD, not trusted and not dropped: an
              innings change (296/9 → 0/0) and a scorer correction (243 → 242) both look
              exactly like a misread until the next read agrees with them.

Templates are per-overlay-font. `templates_from_labels` builds them from labelled crops and
`load_templates` reads them back; `references/frogbox-templates.json` is the FrogBox set.
"""
from __future__ import annotations

import json
import re
from typing import Iterable, Sequence

import numpy as np
from PIL import Image

# --- constants -------------------------------------------------------------------------
# Measured on the FrogBox overlay at 1280×720: navy glyphs (0,63,113) read ~50 in gray, the
# blue cell (84,169,237) reads ~151, so 110 sits in a wide margin between them.
INK = 110
# Height buckets. The score digits are 23 px tall and the overs digits 12, with the brackets
# at 15 — one threshold separates the two type sizes cleanly.
LARGE_MIN_H = 16
# Every glyph is normalised to this box before it is compared with a template.
GLYPH_W, GLYPH_H = 12, 20
CLASSES = "0123456789/()."
DIGITS = "0123456789"
# Cricket priors. Seven runs off one ball is already a boundary plus overthrows; more than
# that is a misread. Two balls between reads covers a sample landing across a quick over.
MAX_RUNS_DELTA = 7
MAX_BALLS_DELTA = 2
# A row this full of ink is a rule/underline, not type.
BORDER_ROW_FRAC = 0.8
# Glyphs of one word sit 1–3 px apart in the FrogBox face; the team-name tail sharing the cell
# is ~27 px away. The threshold is a fraction of the glyph width rather than a flat number,
# because a narrow '1' in a proportional face leaves a 5 px gap after it and a flat 4 would cut
# the word in half there — which is how "13/0" first read back as "3/0".
CONTIGUOUS_GAP = 4
CONTIGUOUS_GAP_FRACTION = 0.6
# A candidate glyph whose runner-up costs within this much is worth carrying to the prior.
CANDIDATE_MARGIN = 0.05
MAX_CANDIDATES = 16
# Per-glyph penalty in the splitter. Cutting a real glyph in half scores both halves badly, so
# total cost already prefers the truth; this only breaks exact ties toward FEWER glyphs.
SPLIT_GLYPH_PENALTY = 0.02


class Glyph:
    """One segmented glyph: its box in the cell and its normalised bitmap."""

    __slots__ = ("x0", "x1", "y0", "y1", "bits", "bucket")

    def __init__(self, x0: int, x1: int, y0: int, y1: int, bits: np.ndarray, bucket: str) -> None:
        self.x0, self.x1, self.y0, self.y1 = int(x0), int(x1), int(y0), int(y1)
        self.bits = bits
        self.bucket = bucket

    @property
    def w(self) -> int:
        return self.x1 - self.x0

    @property
    def h(self) -> int:
        return self.y1 - self.y0

    def box(self) -> list[int]:
        return [self.x0, self.x1, self.y0, self.y1]


class Read:
    """What one cell said. `best` is the decoded string, `candidates` the near-ties."""

    __slots__ = ("best", "candidates", "raw", "glyphs", "runs_text", "overs_text")

    def __init__(self, best: str, candidates: list[str], raw: str, glyphs: list[Glyph],
                 runs_text: str, overs_text: str) -> None:
        self.best, self.candidates, self.raw, self.glyphs = best, candidates, raw, glyphs
        self.runs_text, self.overs_text = runs_text, overs_text

    def as_dict(self) -> dict:
        return {"best": self.best, "candidates": list(self.candidates), "raw": self.raw,
                "glyphs": len(self.glyphs)}


class State:
    """`runs/wkts` plus the ball count, which is the only monotone clock the overlay has."""

    __slots__ = ("runs", "wkts", "balls")

    def __init__(self, runs: int, wkts: int, balls: int) -> None:
        self.runs, self.wkts, self.balls = int(runs), int(wkts), int(balls)

    def __eq__(self, other: object) -> bool:
        return (isinstance(other, State) and other.runs == self.runs
                and other.wkts == self.wkts and other.balls == self.balls)

    def __repr__(self) -> str:
        return f"State({self.runs}/{self.wkts} @ {overs_of(self.balls)})"

    def as_dict(self) -> dict:
        return {"runs": self.runs, "wkts": self.wkts, "balls": self.balls, "overs": overs_of(self.balls)}

    def text(self) -> str:
        return f"{self.runs}/{self.wkts} ({overs_of(self.balls)})"


# --- overs arithmetic ------------------------------------------------------------------
def balls_of(overs: str) -> int:
    """"15.2" → 92. Whole overs may be written "19" or "19.0"."""
    overs = str(overs).strip()
    if not overs:
        raise ValueError("empty overs")
    if "." in overs:
        whole, _, ball = overs.partition(".")
        ball = ball or "0"
    else:
        whole, ball = overs, "0"
    if not whole.isdigit() or not ball.isdigit():
        raise ValueError(f"not an overs string: {overs!r}")
    return int(whole) * 6 + int(ball)


def overs_of(balls: int) -> str:
    """92 → "15.2". A whole over prints bare ("19"), the way the overlay draws it."""
    whole, ball = divmod(int(balls), 6)
    return str(whole) if ball == 0 else f"{whole}.{ball}"


STATE_RE = re.compile(r"^(\d+)/(\d+) \((\d+(?:\.\d)?)\)$")


def parse_state(text: str) -> State | None:
    """"243/6 (44.2)" → State. None when the string is not a complete reading."""
    m = STATE_RE.match(str(text).strip())
    if not m:
        return None
    try:
        return State(int(m.group(1)), int(m.group(2)), balls_of(m.group(3)))
    except ValueError:
        return None


# --- binarise / components -------------------------------------------------------------
def binarise(cell: np.ndarray, ink: int = INK) -> np.ndarray:
    """Ink mask. Rows that are almost solid ink are rules under the type, not type."""
    cell = np.asarray(cell)
    if cell.ndim == 3:                       # tolerate an RGB cell
        cell = np.asarray(Image.fromarray(cell.astype(np.uint8)).convert("L"))
    mask = cell < ink
    if mask.size:
        full = mask.mean(axis=1) > BORDER_ROW_FRAC
        mask[full, :] = False
    return mask


def _column_runs(flags: np.ndarray) -> list[tuple[int, int]]:
    """[(x0, x1)] for each run of True columns."""
    out: list[tuple[int, int]] = []
    x, n = 0, len(flags)
    while x < n:
        if flags[x]:
            x0 = x
            while x < n and flags[x]:
                x += 1
            out.append((x0, x))
        else:
            x += 1
    return out


def components(mask: np.ndarray) -> list[tuple[int, int, int, int]]:
    """Connected runs of non-empty columns → [(x0, x1, y0, y1)]."""
    if mask.size == 0:
        return []
    out = []
    for x0, x1 in _column_runs(mask.any(axis=0)):
        rows = np.flatnonzero(mask[:, x0:x1].any(axis=1))
        out.append((x0, x1, int(rows[0]), int(rows[-1]) + 1))
    return out


def bucket_of(height: int) -> str:
    return "L" if height >= LARGE_MIN_H else "S"


def normalise(mask: np.ndarray) -> np.ndarray:
    """A glyph's ink → a GLYPH_W×GLYPH_H float bitmap in [0, 1]."""
    if mask.size == 0:
        return np.zeros((GLYPH_H, GLYPH_W), dtype=np.float64)
    img = Image.fromarray((mask.astype(np.uint8) * 255))
    return np.asarray(img.resize((GLYPH_W, GLYPH_H), Image.BILINEAR), dtype=np.float64) / 255.0


# --- geometry-only classes -------------------------------------------------------------
def small_baseline(mask: np.ndarray) -> int | None:
    """The row just under the small type, from the overs digits themselves.

    This is what separates a decimal point from a speck: the point sits ON the baseline, and
    the two-pixel blobs that anti-aliasing leaves between digits sit halfway up the x-height.
    Without it the splitter reads "(0.1)" as "(0..1)". The brackets are excluded from the
    measurement — they descend two rows further than the digits do.
    """
    ends = [y1 for _x0, _x1, y0, y1 in components(mask) if 8 <= (y1 - y0) <= 13]
    return max(ends) if ends else None


def geometry_class(sub: np.ndarray, bucket: str, baseline: int | None) -> str | None:
    """'.', '(' or ')' from shape alone, else None.

    These three never go through a template: a 2×2 dot bilinearly resized to 12×20 becomes a
    filled block, which is exactly what a resized '1' becomes. Shape is the only thing that
    tells them apart, so shape is what decides them.
    """
    rows = np.flatnonzero(sub.any(axis=1))
    if rows.size == 0:
        return None
    h = int(rows[-1] - rows[0] + 1)
    w = sub.shape[1]
    if bucket != "S":
        return None
    if (baseline is not None and h <= 4 and w <= 4
            and abs(int(rows[-1]) + 1 - baseline) <= 1
            and float(sub[rows[0]:rows[-1] + 1].mean()) >= 0.5):
        return "."
    if h >= 13 and w <= 5:
        # A bracket leans: '(' carries its ink on the right at the top, ')' on the left.
        top = sub[rows[0]:rows[0] + max(1, h // 3)]
        bottom = sub[rows[-1] - max(1, h // 3) + 1:rows[-1] + 1]
        tx = float(np.flatnonzero(top.any(axis=0)).mean()) if top.any() else 0.0
        bx = float(np.flatnonzero(bottom.any(axis=0)).mean()) if bottom.any() else 0.0
        mid = sub[rows[0] + h // 3:rows[-1] - h // 3 + 1]
        mx = float(np.flatnonzero(mid.any(axis=0)).mean()) if mid.any() else (tx + bx) / 2
        return "(" if mx <= (tx + bx) / 2 else ")"
    return None


GEOMETRY_CLASSES = (".", "(", ")")


# --- templates -------------------------------------------------------------------------
def hydrate_templates(doc: dict) -> dict:
    """A template DOCUMENT (flat lists, as written to JSON) → arrays ready to match against."""
    out: dict = {"font": doc.get("font", "unknown"), "size": list(doc.get("size", [GLYPH_W, GLYPH_H])),
                 "counts": doc.get("counts", {}), "widths": doc.get("widths", {}),
                 "heights": doc.get("heights", {}), "L": {}, "S": {}}
    for bucket in ("L", "S"):
        for char, flat in (doc.get(bucket) or {}).items():
            arr = np.asarray(flat, dtype=np.float64)
            out[bucket][char] = arr.reshape(GLYPH_H, GLYPH_W) if arr.ndim == 1 else arr
    return out


def load_templates(path: str) -> dict:
    """Read a template file. Bitmaps come back as float arrays keyed by bucket then char."""
    with open(path, encoding="utf-8") as fh:
        return hydrate_templates(json.load(fh))


def templates_from_labels(samples: Iterable[tuple[str, str, np.ndarray, int, int]]) -> dict:
    """[(bucket, char, glyph mask, width, height)] → the template document.

    One mean bitmap per (bucket, char), plus the median native width and height of that class.
    The widths are what lets the segmenter split a merged component: they are measured from
    this very font, never assumed.
    """
    bits: dict[str, dict[str, list[np.ndarray]]] = {"L": {}, "S": {}}
    dims: dict[str, dict[str, list[tuple[int, int]]]] = {"L": {}, "S": {}}
    for bucket, char, mask, w, h in samples:
        if bucket not in bits or char not in CLASSES:
            continue
        bits[bucket].setdefault(char, []).append(normalise(mask))
        dims[bucket].setdefault(char, []).append((int(w), int(h)))
    doc: dict = {"font": "frogbox", "size": [GLYPH_W, GLYPH_H], "L": {}, "S": {},
                 "counts": {}, "widths": {"L": {}, "S": {}}, "heights": {"L": {}, "S": {}}}
    for bucket in ("L", "S"):
        for char, stack in sorted(bits[bucket].items()):
            doc[bucket][char] = [round(v, 4) for v in np.mean(stack, axis=0).ravel().tolist()]
            doc["counts"][f"{bucket}{char}"] = len(stack)
            ws = [d[0] for d in dims[bucket][char]]
            hs = [d[1] for d in dims[bucket][char]]
            doc["widths"][bucket][char] = int(round(float(np.median(ws))))
            doc["heights"][bucket][char] = int(round(float(np.median(hs))))
    return doc


def template_widths(templates: dict, bucket: str) -> dict[str, int]:
    return {c: int(w) for c, w in (templates.get("widths", {}).get(bucket) or {}).items()}


def match(glyph_bits: np.ndarray, bank: dict[str, np.ndarray], allow: str | None = None) -> list[tuple[str, float]]:
    """(char, cost) sorted by cost; cost is the mean absolute difference from the template."""
    out = []
    for char, tmpl in bank.items():
        if allow is not None and char not in allow:
            continue
        out.append((char, float(np.abs(glyph_bits - tmpl).mean())))
    out.sort(key=lambda p: p[1])
    return out


# --- segmentation ----------------------------------------------------------------------
def _class_cost(sub: np.ndarray, char: str, bank: dict[str, np.ndarray]) -> float:
    """Cost of calling these columns `char`. The glyph is cropped to its own ink rows first,
    the same way the templates were built — a template compared against a band-height slice
    would be measuring the empty space above and below the type."""
    tmpl = bank.get(char)
    if tmpl is None:
        return 1.0
    rows = np.flatnonzero(sub.any(axis=1))
    if rows.size == 0:
        return 1.0
    return float(np.abs(normalise(sub[rows[0]:rows[-1] + 1]) - tmpl).mean())


def _split_component(comp_mask: np.ndarray, bucket: str, templates: dict,
                     baseline: int | None) -> list[list[int]]:
    """Best column boundaries inside ONE component, by DP against the templates' own widths.

    Merged glyphs are the only segmentation error this font makes, so the job is to find where
    a run of columns should have been cut. Each candidate cut is scored by how well the
    columns either side look like a real glyph of this font, at that glyph's measured width
    (±1 px for anti-aliasing). The DP is COUNT-AWARE — it keeps the best path for every glyph
    count — because "(11)" and "(4)" occupy the same eight columns and only the ball-count
    prior can tell them apart. Returns [[x0, x1], …] relative to the component.
    """
    width = comp_mask.shape[1]
    bank = templates.get(bucket) or {}
    widths = template_widths(templates, bucket)
    if not widths:
        return [[0, width]]
    options: list[tuple[int, str]] = []
    for char, w in widths.items():
        for delta in (-1, 0, 1):
            if w + delta >= 1:
                options.append((w + delta, char))
    options = sorted(set(options))
    if width < 2 * min(widths.values()):
        return [[0, width]]                      # too narrow to hold two glyphs

    # best[x][k] = (cost, previous x) for covering columns [0, x) with k glyphs
    best: list[dict[int, tuple[float, int]]] = [{} for _ in range(width + 1)]
    best[0][0] = (0.0, -1)
    for x in range(width):
        if not best[x]:
            continue
        for w, char in options:
            nx = x + w
            if nx > width:
                continue
            sub = comp_mask[:, x:nx]
            if not sub.any():
                continue
            geo = geometry_class(sub, bucket, baseline) if bucket == "S" else None
            if char in GEOMETRY_CLASSES:
                if geo != char:
                    continue
                cost = 0.0
            else:
                if geo is not None:
                    continue                      # a dot or bracket is never a digit
                rows = np.flatnonzero(sub.any(axis=1))
                h = int(rows[-1] - rows[0] + 1)
                want = (templates.get("heights", {}).get(bucket) or {}).get(char)
                if want is not None and abs(h - int(want)) > 3:
                    continue
                cost = _class_cost(sub, char, bank)
            for k, (base, _prev) in list(best[x].items()):
                total = base + cost + SPLIT_GLYPH_PENALTY
                cur = best[nx].get(k + 1)
                if cur is None or total < cur[0]:
                    best[nx][k + 1] = (total, x)
    if not best[width]:
        return [[0, width]]
    counts = sorted(best[width].items(), key=lambda kv: kv[1][0])
    k, (_cost, _prev) = counts[0]
    # walk the chosen path back
    cuts = [width]
    x, kk = width, k
    while x > 0:
        prev = best[x][kk][1]
        cuts.append(prev)
        x, kk = prev, kk - 1
    cuts.reverse()
    return [[cuts[i], cuts[i + 1]] for i in range(len(cuts) - 1)]


def segment(mask: np.ndarray, templates: dict | None = None) -> list[Glyph]:
    """Mask → glyphs. Without templates this is plain column splitting (the bootstrap pass)."""
    baseline = small_baseline(mask)
    out: list[Glyph] = []
    for x0, x1, y0, y1 in components(mask):
        bucket = bucket_of(y1 - y0)
        sub = mask[:, x0:x1]
        pieces = [[0, x1 - x0]]
        if templates is not None:
            pieces = _split_component(sub, bucket, templates, baseline)
        for a, b in pieces:
            piece = mask[:, x0 + a:x0 + b]
            rows = np.flatnonzero(piece.any(axis=1))
            if rows.size == 0:
                continue
            py0, py1 = int(rows[0]), int(rows[-1]) + 1
            out.append(Glyph(x0 + a, x0 + b, py0, py1,
                             normalise(piece[py0:py1]), bucket_of(py1 - py0) if templates is None else bucket))
    return out


# --- parse -----------------------------------------------------------------------------
def contiguous_gap(boxes: Sequence[tuple[int, int, int, int]]) -> int:
    """How far apart two glyphs of the SAME word can sit, for this face at this size."""
    widths = [b[1] - b[0] for b in boxes]
    if not widths:
        return CONTIGUOUS_GAP
    return max(CONTIGUOUS_GAP, int(round(CONTIGUOUS_GAP_FRACTION * float(np.median(widths)))))


def _runs_by_gap(boxes: Sequence[tuple[int, int, int, int]],
                 gap: int | None = None) -> list[list[tuple[int, int, int, int]]]:
    """Group boxes into words: a gap wider than `gap` starts a new one."""
    if gap is None:
        gap = contiguous_gap(boxes)
    runs: list[list[tuple[int, int, int, int]]] = []
    for box in boxes:
        if runs and box[0] - runs[-1][-1][1] <= gap:
            runs[-1].append(box)
        else:
            runs.append([box])
    return runs


# The two things the cell can say, as state machines. Reading is CONSTRAINED by them rather
# than cleaned up afterwards: "(0.1)" used to come back as "(0..1)" because a two-pixel blob
# between digits is a perfectly good dot in isolation, and no amount of post-hoc tidying can
# tell which of the two dots was real. A grammar can: there is only ever one.
#   score  digits '/' digits
#   overs  '(' digits ('.' one of 1-5)? ')'      — a whole over prints bare, never ".0"
SCORE_GRAMMAR = {0: {"d": 1}, 1: {"d": 1, "/": 2}, 2: {"d": 3}, 3: {"d": 3}}
SCORE_ACCEPT = (3,)
OVERS_GRAMMAR = {0: {"(": 1}, 1: {"d": 2}, 2: {"d": 2, ".": 3, ")": 5}, 3: {"b": 4}, 4: {")": 5}}
OVERS_ACCEPT = (5,)
BALL_DIGITS = "12345"
MAX_PATHS = 6


def _symbol(char: str, state_map: dict) -> str | None:
    """Which transition key a character uses in this grammar ('d' digit, 'b' ball digit)."""
    if char in state_map:
        return char
    if char in BALL_DIGITS and "b" in state_map:
        return "b"
    if char in DIGITS and "d" in state_map:
        return "d"
    return None


def grammar_ok(text: str, grammar: dict, accept: Sequence[int]) -> bool:
    """Does `text` walk this grammar to an accepting state?"""
    state = 0
    for char in text:
        state_map = grammar.get(state) or {}
        sym = _symbol(char, state_map)
        if sym is None:
            return False
        state = state_map[sym]
    return state in accept


def _read_run(mask: np.ndarray, xa: int, xb: int, bucket: str, templates: dict,
              baseline: int | None, grammar: dict,
              accept: Sequence[int]) -> list[tuple[float, str, list[tuple[int, int]]]]:
    """Read the columns [xa, xb) as one word of `grammar`. Returns (cost, text, boxes).

    One dynamic program does segmentation and reading together, so a merged pair of digits and
    a clean one are the same problem: every cut is scored by how well the columns either side
    look like a real glyph of this font at that glyph's own measured width. Empty columns are
    free to skip, which is what lets a word with gaps and a word whose glyphs have fused go
    through the same code.

    Several readings come back, not one, because the picture alone cannot always decide: "(22)"
    and "(2.2)" cover the same columns and both are grammatical. The ball-count prior in
    `decode` is what separates them, and it can only do that if it is offered both.
    """
    bank = templates.get(bucket) or {}
    widths = template_widths(templates, bucket)
    heights = (templates.get("heights", {}).get(bucket) or {})
    if not widths or xb <= xa:
        return []
    ink_cols = mask[:, xa:xb].any(axis=0)
    norm_cache: dict[tuple[int, int], np.ndarray | None] = {}

    def bits_at(x: int, w: int) -> np.ndarray | None:
        key = (x, w)
        if key not in norm_cache:
            sub = mask[:, x:x + w]
            rows = np.flatnonzero(sub.any(axis=1))
            norm_cache[key] = None if rows.size == 0 else normalise(sub[rows[0]:rows[-1] + 1])
        return norm_cache[key]

    options: list[tuple[int, str]] = sorted({(w + d, c) for c, w in widths.items()
                                             for d in (-1, 0, 1) if w + d >= 1})
    # best[(x, state, k)] = (cost, previous key, emitted char)
    best: dict[tuple[int, int, int], tuple[float, tuple | None, str]] = {(xa, 0, 0): (0.0, None, "")}
    frontier = [(xa, 0, 0)]
    seen = {(xa, 0, 0)}
    order: list[tuple[int, int, int]] = []
    while frontier:
        frontier.sort()
        key = frontier.pop(0)
        order.append(key)
        x, state, k = key
        base = best[key][0]
        if x >= xb:
            continue
        if not ink_cols[x - xa]:                       # a gap between words costs nothing
            nk = (x + 1, state, k)
            cur = best.get(nk)
            if cur is None or base < cur[0]:
                best[nk] = (base, key, "")
            if nk not in seen:
                seen.add(nk)
                frontier.append(nk)
            continue
        state_map = grammar.get(state) or {}
        for w, char in options:
            nx = x + w
            if nx > xb:
                continue
            sym = _symbol(char, state_map)
            if sym is None:
                continue
            nstate = state_map[sym]
            sub = mask[:, x:nx]
            if not sub.any():
                continue
            geo = geometry_class(sub, bucket, baseline) if bucket == "S" else None
            if char in GEOMETRY_CLASSES:
                if geo != char:
                    continue
                cost = 0.0
            else:
                if geo is not None:
                    continue                            # a dot or a bracket is never a digit
                rows = np.flatnonzero(sub.any(axis=1))
                want = heights.get(char)
                if want is not None and abs(int(rows[-1] - rows[0] + 1) - int(want)) > 3:
                    continue
                bits = bits_at(x, w)
                tmpl = bank.get(char)
                if bits is None or tmpl is None:
                    continue
                cost = float(np.abs(bits - tmpl).mean())
            nk = (nx, nstate, k + 1)
            total = base + cost + SPLIT_GLYPH_PENALTY
            cur = best.get(nk)
            if cur is None or total < cur[0]:
                best[nk] = (total, key, char)
                if nk in seen and nk in order:
                    continue
            if nk not in seen:
                seen.add(nk)
                frontier.append(nk)
    out: list[tuple[float, str, list[tuple[int, int]]]] = []
    for (x, state, k), (cost, _prev, _char) in best.items():
        if x != xb or state not in accept:
            continue
        text, boxes, cur_key = [], [], (x, state, k)
        while cur_key is not None:
            _c, prev, char = best[cur_key]
            if char:
                text.append(char)
                boxes.append((prev[0], cur_key[0]))
            cur_key = prev
        out.append((cost, "".join(reversed(text)), list(reversed(boxes))))
    out.sort(key=lambda row: (row[0], row[1]))
    seen_text, unique = set(), []
    for cost, text, boxes in out:
        if text not in seen_text:
            seen_text.add(text)
            unique.append((cost, text, boxes))
    return unique[:MAX_PATHS]


def _near_ties(mask: np.ndarray, text: str, boxes: list[tuple[int, int]], bucket: str,
               templates: dict, grammar: dict, accept: Sequence[int]) -> list[tuple[float, str]]:
    """Readings of the SAME cuts with a confusable glyph swapped for its runner-up.

    The path search keeps one reading per (column, grammar state, glyph count), so two words
    that differ only in a character — "(15)" and "(75)" — collapse to whichever scored better,
    and the loser is gone before the prior ever sees it. This puts it back: any glyph whose
    second-best class costs within CANDIDATE_MARGIN of its best is allowed to swap, and the
    combinations that still walk the grammar are offered alongside.
    """
    bank = templates.get(bucket) or {}
    widths = template_widths(templates, bucket)
    slots: list[list[tuple[str, float]]] = []
    for (x0, x1), char in zip(boxes, text):
        if char in GEOMETRY_CLASSES:
            slots.append([(char, 0.0)])
            continue
        sub = mask[:, x0:x1]
        rows = np.flatnonzero(sub.any(axis=1))
        if rows.size == 0:
            slots.append([(char, 0.0)])
            continue
        bits = normalise(sub[rows[0]:rows[-1] + 1])
        allow = "".join(c for c in bank
                        if c not in GEOMETRY_CLASSES and abs(widths.get(c, 0) - (x1 - x0)) <= 1)
        ranked = match(bits, bank, allow=allow or None)
        if len(ranked) >= 2 and (ranked[1][1] - ranked[0][1]) < CANDIDATE_MARGIN:
            slots.append([ranked[0], ranked[1]])
        else:
            slots.append([(char, 0.0)])
    combos: list[tuple[float, str]] = [(0.0, "")]
    for slot in slots:
        nxt = [(cost + c, txt + ch) for cost, txt in combos for ch, c in slot]
        nxt.sort()
        combos = nxt[:MAX_CANDIDATES * 2]
    return [(cost, txt) for cost, txt in combos if grammar_ok(txt, grammar, accept)]


def parse_cell(cell: np.ndarray, templates: dict) -> Read:
    """A grayscale cell → the reading, with its alternatives.

    The anchor rule. The cell also carries the tail of the team-name line, so the score is
    found rather than assumed: the large glyphs are grouped into words by their gaps, and the
    longest word that parses as `R/W` wins. The overs are then read from the small glyphs to
    the RIGHT of it. Anything else — the team-name tail, a stray speck — is dropped.
    """
    mask = binarise(cell)
    baseline = small_baseline(mask)
    boxes = components(mask)
    large = [b for b in boxes if bucket_of(b[3] - b[2]) == "L"]
    small = [b for b in boxes if bucket_of(b[3] - b[2]) == "S"]

    def readings(xa: int, xb: int, bucket: str, grammar: dict,
                 accept: Sequence[int]) -> list[tuple[float, str]]:
        paths = _read_run(mask, xa, xb, bucket, templates, baseline, grammar, accept)
        if not paths:
            return []
        _cost, text, boxes = paths[0]
        out = _near_ties(mask, text, boxes, bucket, templates, grammar, accept) if boxes else []
        out += [(c, t) for c, t, _boxes in paths]
        out.sort()
        seen_t, uniq = set(), []
        for cost, text in out:
            if text not in seen_t:
                seen_t.add(text)
                uniq.append((cost, text))
        return uniq[:MAX_CANDIDATES]

    score_paths: list[tuple[float, str]] = []
    right = -1
    for run in _runs_by_gap(large):
        xa, xb = run[0][0], run[-1][1]
        paths = readings(xa, xb, "L", SCORE_GRAMMAR, SCORE_ACCEPT)
        if not paths:
            continue
        # the longest word that reads as a score wins; ties go to the cheaper reading
        if not score_paths or len(paths[0][1]) > len(score_paths[0][1]):
            score_paths, right = paths, xb
    overs_paths: list[tuple[float, str]] = []
    overs_boxes = [b for b in small if b[0] >= right]
    if overs_boxes:
        overs_paths = readings(overs_boxes[0][0], overs_boxes[-1][1], "S",
                               OVERS_GRAMMAR, OVERS_ACCEPT)

    score_text = score_paths[0][1] if score_paths else ""
    overs_text = overs_paths[0][1] if overs_paths else ""
    raw = f"{score_text} {overs_text}".strip()
    combos: list[tuple[float, str]] = []
    for sc, stext in score_paths or [(0.0, "")]:
        for oc, otext in overs_paths or [(0.0, "")]:
            combos.append((sc + oc, f"{stext} {otext}".strip()))
    combos.sort()
    seen, candidates = set(), []
    for _cost, text in combos:
        if text not in seen:
            seen.add(text)
            candidates.append(text)
    best = candidates[0] if candidates else raw
    glyphs = segment(mask, templates)
    return Read(best, candidates[:MAX_CANDIDATES], raw, glyphs, score_text, overs_text)


# --- prior, decode, commit -------------------------------------------------------------
def prior_ok(prev: State | None, cur: State) -> bool:
    """Is `cur` a state the match could actually have reached from `prev`?"""
    if cur.runs < 0 or cur.wkts < 0 or cur.balls < 0 or cur.wkts > 10:
        return False
    if cur.balls % 6 > 5:
        return False
    if prev is None:
        return True
    d_runs = cur.runs - prev.runs
    d_wkts = cur.wkts - prev.wkts
    d_balls = cur.balls - prev.balls
    if d_runs < 0 or d_runs > MAX_RUNS_DELTA:
        return False
    if d_wkts not in (0, 1, 2):
        return False
    if d_balls < 0 or d_balls > MAX_BALLS_DELTA:
        return False
    return True


def decode(read: Read, prev: State | None) -> tuple[State | None, str, str]:
    """(state, text, flag). The cheapest candidate the prior accepts; else the raw best."""
    for text in read.candidates:
        state = parse_state(text)
        if state is not None and prior_ok(prev, state):
            return state, text, ""
    state = parse_state(read.best)
    if state is None:
        return None, read.best, "unreadable"
    return state, read.best, "violation"


def commit_policy(pending: State | None, cur: State | None, last: State | None) -> tuple[str, State | None]:
    """Two-read confirmation for a state the prior refused.

    An innings change and a scorer's correction are both indistinguishable from a misread at
    the moment they appear — the only thing that separates them is whether the NEXT read
    agrees. So a violating read is held, and committed only when the read after it is
    consistent with it.

    Returns (verdict, state): "none" when nothing is pending, "innings" / "correction" when
    the held read is confirmed, "drop" when it was a misread.
    """
    if pending is None:
        return "none", None
    if cur is None:
        return "drop", None
    if not prior_ok(pending, cur):
        return "drop", None
    small = pending.runs <= 6 and pending.balls <= 6
    if small and last is not None and (last.runs > 20 or last.balls > 36):
        return "innings", pending
    return "correction", pending


# --- outcome ---------------------------------------------------------------------------
def outcome(prev: State, cur: State) -> dict:
    """What the ball did, from the two states either side of it.

    A ball that scores without advancing the over is an extra, so `extra` comes from Δballs
    and the batter's runs are what is left. The TYPE is taken from the batter's runs, which is
    why a no-ball four still reaches the highlights reel as a four.

    Documented ambiguity: the overlay cannot separate a wide from a wide-with-byes, and
    penalty or retired runs entered between balls read as a wide or a no-ball.
    """
    d_runs = cur.runs - prev.runs
    d_wkts = cur.wkts - prev.wkts
    d_balls = cur.balls - prev.balls
    extra = 1 if (d_balls == 0 and d_runs >= 1) else 0
    bat = d_runs - extra
    if d_wkts >= 1:
        kind = "wicket"
    elif bat == 6:
        kind = "six"
    elif bat == 4:
        kind = "four"
    elif d_balls == 0 and d_runs == 1:
        kind = "wide"
    elif d_balls == 0:
        kind = "noball"
    elif d_runs == 0:
        kind = "dot"
    else:
        kind = "runs"
    return {"t": kind, "runs": d_runs, "bat": bat, "extra": extra, "wkts": d_wkts, "balls": d_balls}


__all__ = [
    "INK", "LARGE_MIN_H", "GLYPH_W", "GLYPH_H", "CLASSES", "MAX_RUNS_DELTA", "MAX_BALLS_DELTA",
    "Glyph", "Read", "State", "balls_of", "overs_of", "parse_state", "binarise", "components",
    "segment", "normalise", "geometry_class", "small_baseline", "match", "parse_cell",
    "prior_ok", "decode", "grammar_ok", "contiguous_gap",
    "commit_policy", "outcome", "templates_from_labels", "load_templates", "hydrate_templates",
    "template_widths",
]
