"""Sidecar/1: a versioned per-frame envelope for the SEI sidecar, with a validator and a rebinder.

`sidecar.py` moves bytes (one SEI NAL per access unit). This module says what the bytes MEAN:
one JSON object per frame that carries, for every measurement, the ANSWERABILITY record that
produced it -- which model, how many pixels were on the target, whether the gate passed, what the
scalar baseline scored on the card -- plus a 64-bit fingerprint of the frame so the binding can be
recovered after a transcode strips the SEI (measured: SEI survives remux 300/300, dies on a
default transcode 0/300).

Spec: docs/SIDECAR1.md (Sidecar/1, 2026-09-05, resoa / loglens).

    from nanolab import sidecar1 as s1
    env = s1.make(f=17, t=1757000000.0, fp=s1.fingerprint(luma), src={"cam": "bay2", "res": [1920, 1080], "tx_res": [640, 360]},
                  m=[s1.row("occupancy", True, p=0.91, by={"model": "occ-nano", "ver": "3f9a", "kind": "nano"},
                            gate=s1.gate(px_on_target=41.0, task="detect", lux=120), base={"scalar": "thermal_var", "margin": 0.08})])
    assert s1.validate(env) == []
    inject_mp4(src, dst, json_payload(lambda d: envelopes[d]))          # transport is sidecar.py's job

Everything here is numpy-only and deterministic; the fingerprint is specified step by step in the
doc so a JS receiver (WebRTC Encoded Transform, or a canvas after decode) can reproduce it.
"""
import json
import numpy as np
from .answerability import DETECT, RECOGNISE, IDENTIFY

VERSION = "sidecar/1"
KINDS = ("nano", "scalar", "lookup", "sensor")
TASKS = ("detect", "recognise", "identify")
SPACES = ("orig", "tx")
SIZE_GUIDANCE_B = 600          # ~300-600 B/frame at 30 fps is 100-150 kbit/s, <2% of an 8 Mbit/s stream
SIZE_WARN_B = 2 * SIZE_GUIDANCE_B   # the validator warns above this (~4% of 8 Mbit/s); a full row is ~230 B
_THR = {"detect": DETECT, "recognise": RECOGNISE, "identify": IDENTIFY}


# ------------------------------------------------------------------ builders
def gate(px_on_target=None, task="recognise", lux=None, snr_db=None, passed=None):
    """Answerability record for one row. `passed` defaults to px_on_target >= the Johnson threshold
    for `task` (2 / 8 / 12.8 px) when px_on_target is known, else False -- a gate nobody evaluated
    did not pass."""
    if task not in TASKS:
        raise ValueError(f"task must be one of {TASKS}")
    if passed is None:
        passed = px_on_target is not None and float(px_on_target) >= _THR[task]
    return {"px_on_target": None if px_on_target is None else float(px_on_target), "task": task,
            "lux": lux, "snr_db": snr_db, "passed": bool(passed)}


def row(k, val, p=None, by=None, gate=None, base=None, box=None, refused=False, why=None, space=None):
    """One measurement row. Keys with value None are omitted (compact on the wire); `ref` appears
    only when the measurement was refused, and then `why` is mandatory."""
    if not isinstance(k, str) or not k:
        raise ValueError("k must be a non-empty string")
    r = {"k": k, "val": val}
    if p is not None: r["p"] = float(p)
    if by is not None: r["by"] = dict(by)
    if gate is not None: r["gate"] = dict(gate)
    if base is not None: r["base"] = dict(base)
    if refused:
        if not why:
            raise ValueError("a refused row must say why")
        r["ref"] = True; r["why"] = str(why)
    if box is not None:
        if len(box) != 4:
            raise ValueError("box is [x, y, w, h]")
        r["box"] = [float(v) for v in box]
    if space is not None: r["space"] = space
    return r


def make(f, t, m, fp=None, src=None):
    """One frame's envelope. `d` (decode index) is NOT set here: sidecar.json_payload stamps it at
    injection time, which is the only place the decode order is known."""
    env = {"v": VERSION, "f": int(f)}
    if t is not None: env["t"] = float(t)
    if fp is not None: env["fp"] = fp
    if src is not None: env["src"] = dict(src)
    env["m"] = list(m)
    return env


# ------------------------------------------------------------------ validator
def _is_num(x): return isinstance(x, (int, float)) and not isinstance(x, bool)
def _is_int(x): return isinstance(x, int) and not isinstance(x, bool)


def _check_res(v, name, out):
    if not (isinstance(v, list) and len(v) == 2 and all(_is_int(a) and a > 0 for a in v)):
        out.append(f"error: src.{name} must be [w, h] of positive ints")


def _check_row(i, r, out):
    tag = f"m[{i}]"
    if not isinstance(r, dict):
        out.append(f"error: {tag} must be an object"); return
    k = r.get("k")
    if not isinstance(k, str) or not k:
        out.append(f"error: {tag}.k must be a non-empty string")
    else:
        tag = f"m[{i}] ({k})"
    if "val" not in r:
        out.append(f"error: {tag}.val is required (use null if there is no value)")
    p = r.get("p")
    if p is not None and not (_is_num(p) and 0.0 <= p <= 1.0):
        out.append(f"error: {tag}.p must be a probability in [0, 1] or null")
    by = r.get("by")
    if by is not None:
        if not isinstance(by, dict):
            out.append(f"error: {tag}.by must be an object")
        else:
            for key in ("model", "ver"):
                if not isinstance(by.get(key), str):
                    out.append(f"error: {tag}.by.{key} must be a string")
            if by.get("kind") not in KINDS:
                out.append(f"error: {tag}.by.kind must be one of {'|'.join(KINDS)}")
    g = r.get("gate")
    if g is None:
        out.append(f"warning: {tag} has no gate -- second-class row; p alone is not a validity signal")
    elif not isinstance(g, dict):
        out.append(f"error: {tag}.gate must be an object")
    else:
        if not isinstance(g.get("passed"), bool):
            out.append(f"error: {tag}.gate.passed must be true or false")
        px = g.get("px_on_target")
        if px is not None and not _is_num(px):
            out.append(f"error: {tag}.gate.px_on_target must be a number or null")
        if "task" in g and g["task"] not in TASKS:
            out.append(f"error: {tag}.gate.task must be one of {'|'.join(TASKS)}")
        for key in ("lux", "snr_db"):
            if g.get(key) is not None and not _is_num(g[key]):
                out.append(f"error: {tag}.gate.{key} must be a number or null")
    b = r.get("base")
    if b is not None:
        if not isinstance(b, dict):
            out.append(f"error: {tag}.base must be an object")
        else:
            if not isinstance(b.get("scalar"), str):
                out.append(f"error: {tag}.base.scalar must be a string")
            if b.get("margin") is not None and not _is_num(b["margin"]):
                out.append(f"error: {tag}.base.margin must be a number or null")
    ref = r.get("ref")
    if ref is not None and not isinstance(ref, bool):
        out.append(f"error: {tag}.ref must be true or false")
    if ref is True and not (isinstance(r.get("why"), str) and r["why"]):
        out.append(f"error: {tag} is refused (ref=true) but has no why")
    box = r.get("box")
    if box is not None and not (isinstance(box, list) and len(box) == 4 and all(_is_num(v) for v in box)):
        out.append(f"error: {tag}.box must be [x, y, w, h]")
    if "space" in r and r["space"] not in SPACES:
        out.append(f"error: {tag}.space must be orig|tx")


def validate(obj):
    """-> list of 'error: ...' and 'warning: ...' strings; empty means valid. Unknown keys anywhere
    are ignored, never reported (forward compatibility). A row without `gate` warns; a payload
    over SIZE_WARN_B bytes compact warns."""
    out = []
    if not isinstance(obj, dict):
        return ["error: envelope must be a JSON object"]
    v = obj.get("v")
    if v is None:
        out.append("error: v is required (expected 'sidecar/1')")
    elif v != VERSION:
        out.append(f"error: v is {v!r}, expected {VERSION!r}")
    if not _is_int(obj.get("f")) or obj["f"] < 0:
        out.append("error: f (display frame index) must be a non-negative int")
    if "d" in obj and not (_is_int(obj["d"]) and obj["d"] >= 0):
        out.append("error: d (decode index) must be a non-negative int")
    if "t" in obj and not _is_num(obj["t"]):
        out.append("error: t must be a number (seconds or unix time)")
    fp = obj.get("fp")
    if fp is not None and not (isinstance(fp, str) and len(fp) == 16 and all(c in "0123456789abcdef" for c in fp)):
        out.append("error: fp must be 16 lowercase hex chars (64-bit pHash)")
    src = obj.get("src")
    if src is not None:
        if not isinstance(src, dict):
            out.append("error: src must be an object")
        else:
            if "cam" in src and not isinstance(src["cam"], str):
                out.append("error: src.cam must be a string")
            for name in ("res", "tx_res"):
                if name in src: _check_res(src[name], name, out)
    m = obj.get("m")
    if m is None:
        out.append("warning: m is absent -- an envelope with no measurement rows says nothing about the frame")
    elif not isinstance(m, list):
        out.append("error: m must be a list of measurement rows")
    else:
        for i, r in enumerate(m):
            _check_row(i, r, out)
    try:
        n = len(json.dumps(obj, separators=(",", ":")).encode())
        if n > SIZE_WARN_B:
            out.append(f"warning: payload is {n} B compact, twice the {SIZE_GUIDANCE_B} B/frame guidance")
    except (TypeError, ValueError):
        out.append("error: envelope is not JSON-serialisable")
    return out


# ------------------------------------------------------------------ fingerprint
_N, _K = 32, 8


def _dct_rows(n=_N, k=_K):
    """First k rows of the orthonormal DCT-II matrix for length n: D[u,x] = c(u) cos(pi (2x+1) u / 2n)."""
    x = np.arange(n, dtype=np.float64); u = np.arange(k, dtype=np.float64)[:, None]
    D = np.cos(np.pi * (2 * x + 1) * u / (2 * n))
    D[0] *= np.sqrt(1.0 / n); D[1:] *= np.sqrt(2.0 / n)
    return D


_D = _dct_rows()


def downscale32(gray):
    """Step 1 of the fingerprint: 32x32 block mean with integer boundaries. Cell i of an axis of
    length L covers input indices [floor(i*L/32), max(floor((i+1)*L/32), floor(i*L/32)+1))."""
    g = np.asarray(gray, dtype=np.float64)
    if g.ndim != 2:
        raise ValueError("fingerprint wants a 2-D luma array")
    H, W = g.shape
    if H < 1 or W < 1:
        raise ValueError("empty image")

    def bounds(L):
        lo = [(i * L) // _N for i in range(_N)]
        return [(a, max((i + 1) * L // _N, a + 1)) for i, a in enumerate(lo)]

    rows = np.stack([g[a:b].mean(axis=0) for a, b in bounds(H)])          # 32 x W
    return np.stack([rows[:, a:b].mean(axis=1) for a, b in bounds(W)], axis=1)   # 32 x 32


def fingerprint(gray):
    """64-bit pHash of a luma image -> 16 lowercase hex chars. Deterministic; see docs/SIDECAR1.md
    for the exact steps (32x32 block mean, orthonormal 2-D DCT-II, top-left 8x8, bit = coef > median
    of the 64, row-major, MSB first)."""
    s = downscale32(gray)
    C = _D @ s @ _D.T                                    # 8 x 8 low-frequency block
    c = C.ravel()
    srt = np.sort(c); med = 0.5 * (srt[31] + srt[32])
    bits = c > med
    val = 0
    for b in bits:
        val = (val << 1) | int(b)
    return f"{val:016x}"


def hamming(fp_a, fp_b):
    """Bits that differ between two fingerprints (0..64)."""
    return bin(int(fp_a, 16) ^ int(fp_b, 16)).count("1")


# ------------------------------------------------------------------ rebind
_POP8 = np.array([bin(i).count("1") for i in range(256)], dtype=np.int64)
_INF = 1e18


def _u64(fps):
    return np.array([int(x, 16) for x in fps], dtype=np.uint64)


def _popcount(x):
    """Population count of a uint64 array (numpy < 2.0 has no bitwise_count)."""
    x = np.ascontiguousarray(x, dtype=np.uint64)
    return _POP8[x.view(np.uint8).reshape(x.shape + (8,))].sum(axis=-1)


def _row_fps(rows):
    """(fingerprints as uint64 with 0 for rows that have none, mask of rows that have one)."""
    has = np.array([bool(isinstance(r, dict) and r.get("fp")) for r in rows], dtype=bool)
    return _u64([r["fp"] if h else "0" for r, h in zip(rows, has)]), has


def rebind(rows, frames_fps, window=60, gap=6.0):
    """Re-associate envelope rows to decoded frames after the SEI binding is lost, by MONOTONE
    sequence alignment of fingerprints (banded Needleman-Wunsch).

    rows        envelopes in time order (dicts with 'fp'). A row WITHOUT a fingerprint still holds
                its place in the sequence: it aligns as a zero-cost wildcard and comes back with the
                frame its position implies and hamming None (no evidence, only order).
    frames_fps  fingerprint of each decoded frame, in the receiver's decode order
    window      band half-width: row i may only align to frames i-window .. i+window
    gap         cost of skipping one row or one frame (a match costs its Hamming distance, so a
                pair is matched only when it is cheaper than two skips, i.e. Hamming < 2*gap)
    -> list, one (frame_index or None, hamming or None) per row.

    WHY ALIGNMENT AND NOT NEAREST NEIGHBOUR. Consecutive frames 33 ms apart differ by ~4 bits of
    the 64-bit pHash (median 4, p10 2 on a moving synthetic scene), which is inside the survival
    tolerance of a transcode (p99 4 bits after 2x downscale + CRF 28). Nearest neighbour therefore
    picks a look-alike neighbour for 14% of frames (0.86 correct); both sequences are in time
    order, and using that order recovers 1.00, also with 2% of frames dropped (measured 2026-09-05,
    600 frames). `rebind_nearest` keeps the naive version for comparison.
    """
    R, has = _row_fps(rows)
    F = _u64(frames_fps)
    n, m, w = len(R), len(F), int(window)
    out = [(None, None)] * len(rows)
    if n == 0 or m == 0 or not has.any():
        return out
    W2 = 2 * w + 1
    D = np.full((n + 1, W2), _INF)                       # D[i, j - i + w] = cost of aligning R[:i] with F[:j]
    js0 = np.arange(0, min(m, w) + 1)
    D[0, js0 + w] = gap * js0                            # leading frames skipped
    H = np.zeros((n, W2), dtype=np.int64)                # Hamming of R[i-1] vs F[j-1], banded like D
    for i in range(1, n + 1):
        js = np.arange(max(0, i - w), min(m, i + w) + 1)
        cs = js - i + w
        diag = np.full(js.shape, _INF)
        pos = js >= 1
        h = _popcount(R[i - 1] ^ F[js[pos] - 1]) if has[i - 1] else np.zeros(int(pos.sum()), dtype=np.int64)
        H[i - 1, cs[pos]] = h
        diag[pos] = D[i - 1, cs[pos]] + h                # D[i-1, j-1] sits in the same band column
        up = np.full(js.shape, _INF)
        ok = cs + 1 < W2
        up[ok] = D[i - 1, cs[ok] + 1] + gap             # D[i-1, j]: skip row i
        A = np.minimum(diag, up)
        D[i, cs] = np.minimum.accumulate(A - gap * js) + gap * js   # D[i, j-1] + gap: skip frame j, as a prefix scan
    # backtrack from the last in-band cell
    i, j = n, min(m, n + w)
    if n > m + w:
        i = m + w
    eps = 1e-6
    while i > 0 and j > 0:
        c = j - i + w
        cost = D[i, c]
        if abs(D[i - 1, c] + H[i - 1, c] - cost) < eps:          # match
            out[i - 1] = (j - 1, int(H[i - 1, c]) if has[i - 1] else None); i -= 1; j -= 1
        elif c + 1 < W2 and abs(D[i - 1, c + 1] + gap - cost) < eps:   # row skipped
            i -= 1
        elif c - 1 >= 0 and abs(D[i, c - 1] + gap - cost) < eps:       # frame skipped
            j -= 1
        else:
            break
    return out


def rebind_nearest(rows, frames_fps, max_hamming=6, window=60, offset=0):
    """Nearest-neighbour rebinding, kept for comparison with `rebind`: for each row the frame within
    +-window of its anchor (f + offset, else list position) with the smallest Hamming distance,
    ties to the candidate nearest the anchor. Measured 0.86 correct where alignment gets 1.00,
    because near-identical neighbours are inside the tolerance. -> list of (frame_index or None,
    hamming or None) per row."""
    fr = _u64(frames_fps)
    out = []
    for i, r in enumerate(rows):
        fp = r.get("fp") if isinstance(r, dict) else None
        if not fp:
            out.append((None, None)); continue
        a = np.uint64(int(fp, 16))
        anchor = (r["f"] if _is_int(r.get("f")) else i) + offset
        lo, hi = max(0, anchor - window), min(len(fr), anchor + window + 1)
        if hi <= lo:
            out.append((None, None)); continue
        js = np.arange(lo, hi); ds = _popcount(a ^ fr[js])
        order = np.lexsort((np.abs(js - anchor), ds))
        j, d = int(js[order[0]]), int(ds[order[0]])
        out.append((j, d) if d <= max_hamming else (None, d))
    return out


def ambiguous(frames_fps, max_hamming=4, window=60):
    """Fraction of decoded frames that have a look-alike (another frame within +-window at Hamming
    <= max_hamming). ~1.0 on a static scene, where the fingerprint carries no ordering information
    and alignment output is arbitrary within runs (measured 0.10 and 1.00 correct on two
    degradations of the same static clip): the receiver must fall back to timestamps / decode
    index. On a moving scene with slow motion the flag can also fire -- that is the case
    alignment handles -- so read it together with the consecutive-frame Hamming median (4 on the
    moving clip, 0 on the static one)."""
    F = _u64(frames_fps); m = len(F)
    if m == 0:
        return 0.0
    flagged = 0
    for j in range(m):
        lo, hi = max(0, j - window), min(m, j + window + 1)
        cand = np.concatenate([np.arange(lo, j), np.arange(j + 1, hi)])
        if cand.size and (_popcount(F[j] ^ F[cand]) <= max_hamming).any():
            flagged += 1
    return flagged / m
