"""Build the samples for the sidecar demo Space (Sidecar/1 envelopes + a stripped transcode).

clean.mp4 (libx264, -bf 3, faststart, no audio, 640x360, 600 frames)
  -> sidecar.mp4             one Sidecar/1 JSON envelope per access unit as SEI (Tab A: in-band)
  -> sidecar_transcoded.mp4  libx264 CRF 28 at 480x270: the re-encode drops every SEI (Tab B)
  -> sidecar_rows.json       the 600 envelopes in time order (the out-of-band copy a receiver might
                             hold from a data channel), without the transport's decode index
  -> parity.json             Tab A: first 10 raw payloads; Tab B: Python fingerprints of the decoded
                             transcoded frames and the Python `rebind` result, so the page can check
                             its own fingerprint + alignment against the reference

Per DISPLAY frame: cheap pixel statistics (mean luma, Laplacian variance, changed 16x16 blocks) as
`by.kind = "scalar"` rows with a gate, plus the 64-bit fingerprint of the frame's Y plane.
"""
import json, struct, subprocess, sys, time
from pathlib import Path

import cv2, numpy as np

sys.path.insert(0, "/mnt/fast/vidgen/dist/nanolab")
from nanolab import sidecar, sidecar1 as s1
from nanolab.sidecar import _boxes, _find, _read_table

SRC = Path("/mnt/fast/vidgen/out/sidecar/demo/clean.mp4")
OUT = Path("/mnt/fast/vidgen/dist/spaces/sidecar-demo")
DST = OUT / "sidecar.mp4"
TX = OUT / "sidecar_transcoded.mp4"
TX_RES = (480, 270)
FFMPEG, FFPROBE = "/usr/bin/ffmpeg", "/usr/bin/ffprobe"
CHECK_VECTOR = "aa0a7f817e817e85"


def sample_pts(path):
    """-> (timescale, [pts per sample in decode order]) from stts/ctts."""
    data = path.read_bytes()
    top = list(_boxes(data, 0, len(data)))
    moov = next(b for b in top if b[0] == b"moov")
    trak = next(b for b in _boxes(data, moov[1] + moov[3], moov[1] + moov[2]) if b[0] == b"trak")
    _, tp, tsz, thd = trak
    mdhd = _find(data, tp + thd, tp + tsz, [b"mdia", b"mdhd"])
    body = mdhd[0] + mdhd[2]
    ver = data[body]
    timescale = struct.unpack(">I", data[body + (20 if ver == 1 else 12):][:4])[0]
    stbl = _find(data, tp + thd, tp + tsz, [b"mdia", b"minf", b"stbl"]); sp, ssz, shd = stbl
    stts = _find(data, sp + shd, sp + ssz, [b"stts"]); ctts = _find(data, sp + shd, sp + ssz, [b"ctts"])
    _, stts_e, _ = _read_table(data, stts, "II", 4, 8)
    durs = []
    for cnt, dur in stts_e: durs += [dur] * cnt
    offs = [0] * len(durs)
    if ctts:
        _, ctts_e, _ = _read_table(data, ctts, "Ii", 4, 8)
        k = 0
        for cnt, off in ctts_e:
            for _ in range(cnt): offs[k] = off; k += 1
        assert k == len(durs)
    dts, pts = 0, []
    for d, o in zip(durs, offs): pts.append(dts + o); dts += d
    return timescale, pts


def ffprobe_pts(path):
    p = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v", "-show_entries",
                        "packet=pts", "-of", "csv=p=0", str(path)], capture_output=True, text=True, check=True)
    return [int(x) for x in p.stdout.split() if x.strip()]


def luma_planes(path, w, h):
    """Decoded Y planes in display order, straight from the decoder: the Y plane of the raw yuv420p
    output (NOT `-pix_fmt gray`, which on ffmpeg 8 applies a limited-to-full range conversion)."""
    p = subprocess.run([FFMPEG, "-v", "error", "-i", str(path), "-an", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"],
                       capture_output=True, check=True)
    fsz = w * h * 3 // 2; n = len(p.stdout) // fsz; assert n * fsz == len(p.stdout)
    return np.frombuffer(p.stdout, np.uint8).reshape(n, fsz)[:, :w * h].reshape(n, h, w)


def analyse(path):
    """Cheap per-frame statistics (display order) from the decoded picture."""
    cap = cv2.VideoCapture(str(path)); recs, prev = [], None
    while True:
        ok, fr = cap.read()
        if not ok: break
        g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
        lum = float(g.mean())
        sharp = float(cv2.Laplacian(g, cv2.CV_64F).var())
        if prev is None: changed = 0
        else:
            diff = np.abs(g[:352].astype(np.int16) - prev[:352].astype(np.int16))
            blk = diff.reshape(22, 16, 40, 16).mean(axis=(1, 3))          # 40 x 22 blocks of 16x16 (last 8 rows dropped)
            changed = int((blk > 6).sum())
        prev = g
        recs.append({"lum": round(lum, 2), "sharp": round(sharp, 1), "changed_blocks": changed})
    return recs


def envelope(i, t, rec, fp, ver):
    """One Sidecar/1 envelope: three scalar rows, each with an explicit whole-frame gate (as the
    `cct` row in docs/SIDECAR1.md section 3), the frame fingerprint, and the source resolutions."""
    g = s1.gate(px_on_target=None, task="detect", passed=True)
    rows = [s1.row("lum", rec["lum"], by={"model": "mean_gray", "ver": ver, "kind": "scalar"}, gate=g),
            s1.row("sharp", rec["sharp"], by={"model": "laplacian_var", "ver": ver, "kind": "scalar"}, gate=g),
            s1.row("changed_blocks", rec["changed_blocks"], by={"model": "blockdiff16_thr6", "ver": "1", "kind": "scalar"}, gate=g)]
    return s1.make(f=i, t=t, m=rows, fp=fp, src={"res": [640, 360], "tx_res": [640, 360]})


def count_sei(path):
    return sum(1 for g in sidecar.extract(path) if g)


def survival(dst, n, tmp):
    """What copy paths and the re-encode do to THIS file (nanolab.sidecar.extract after each)."""
    run = lambda *a: subprocess.run([FFMPEG, "-y", "-v", "error", *a], check=True)
    out = {}
    run("-i", str(dst), "-an", "-c", "copy", str(tmp / "r.mkv")); run("-i", str(tmp / "r.mkv"), "-an", "-c", "copy", str(tmp / "r.mp4"))
    out["remux mp4 -> mkv -> mp4"] = [count_sei(tmp / "r.mp4"), n]
    run("-i", str(dst), "-an", "-c", "copy", "-f", "mpegts", str(tmp / "r.ts"))
    out["MPEG-TS remux"] = [count_sei(tmp / "r.ts"), n]
    run("-i", str(dst), "-an", "-c", "copy", "-f", "hls", "-hls_time", "2", "-hls_list_size", "0", str(tmp / "hls.m3u8"))
    out["HLS, 2 s TS segments"] = [count_sei(tmp / "hls.m3u8"), n]
    run("-i", str(dst), "-an", "-c", "copy", "-movflags", "frag_keyframe+empty_moov", str(tmp / "frag.mp4"))
    out["fragmented mp4 (CMAF style)"] = [count_sei(tmp / "frag.mp4"), n]
    run("-i", str(dst), "-an", "-c:v", "libx264", "-crf", "24", str(tmp / "x.mp4"))
    out["libx264 transcode, same size, CRF 24"] = [count_sei(tmp / "x.mp4"), n]
    return out


def main():
    ver = cv2.__version__
    assert s1.fingerprint((np.arange(64, dtype=np.float64)[:, None] * 4 + np.arange(64)[None, :] * 0.5).astype(np.uint8)) == CHECK_VECTOR
    timescale, pts = sample_pts(SRC)
    fpr = ffprobe_pts(SRC)
    assert [p - min(pts) for p in pts] == [p - min(fpr) for p in fpr], "stts/ctts pts disagree with ffprobe"
    n = len(pts); order = sorted(range(n), key=lambda d: pts[d])
    display_of = {d: i for i, d in enumerate(order)}
    t0 = min(pts)

    Y = luma_planes(SRC, 640, 360); assert Y.shape[0] == n
    recs = analyse(SRC); assert len(recs) == n, (len(recs), n)
    fps_src = [s1.fingerprint(Y[i]) for i in range(n)]
    envs = [envelope(i, round((pts[order[i]] - t0) / timescale, 4), recs[i], fps_src[i], ver) for i in range(n)]
    problems = [(i, v) for i, e in enumerate(envs) for v in s1.validate(e)]
    assert not problems, problems[:5]
    sizes = [len(json.dumps(e, separators=(",", ":")).encode()) for e in envs]
    print(f"{n} frames, timescale {timescale}; envelopes validate clean, {min(sizes)}-{max(sizes)} B compact (mean {np.mean(sizes):.0f})")

    # ---- inject: the payload function is keyed by DECODE index
    stats = sidecar.inject_mp4(SRC, DST, sidecar.json_payload(lambda d: envs[display_of[d]]))
    print("inject:", stats)
    got = sidecar.extract(DST)
    assert len(got) == n and all(len(g) == 1 for g in got), "not every frame carries a payload"
    parsed = [json.loads(g[0]) for g in got]
    assert all(p["d"] == d and p["f"] == display_of[d] and p["v"] == s1.VERSION for d, p in enumerate(parsed))
    assert all(s1.validate(p) == [] for p in parsed)
    print(f"extract: {n}/{n} samples carry a Sidecar/1 envelope, all validate clean; {DST.stat().st_size} bytes")
    assert DST.stat().st_size < 5_000_000

    # ---- the transcode: re-encode at a new resolution; SEI does not survive a re-encode
    subprocess.run([FFMPEG, "-y", "-v", "error", "-i", str(DST), "-an", "-vf", f"scale={TX_RES[0]}:{TX_RES[1]}",
                    "-c:v", "libx264", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(TX)], check=True)
    tx_sei = count_sei(TX)
    Ytx = luma_planes(TX, *TX_RES); m = Ytx.shape[0]
    print(f"transcode {TX.name}: {TX.stat().st_size} bytes, {m} frames, SEI {tx_sei}/{m}")
    assert tx_sei == 0 and m == n

    # ---- rebind by fingerprint (the Python reference the page checks itself against)
    t1 = time.time()
    fps_tx = [s1.fingerprint(Ytx[j]) for j in range(m)]
    rb = s1.rebind(envs, fps_tx, window=60, gap=6.0)
    t_rebind = time.time() - t1
    matched = [(i, j, h) for i, (j, h) in enumerate(rb) if j is not None]
    correct = sum(1 for i, j, h in matched if j == envs[i]["f"])
    hams = np.array([h for _, _, h in matched])
    nn = s1.rebind_nearest(envs, fps_tx, max_hamming=6, window=60)
    nn_correct = sum(1 for i, (j, h) in enumerate(nn) if j == envs[i]["f"])
    amb = s1.ambiguous(fps_tx, max_hamming=4, window=60)
    consec = np.median([s1.hamming(fps_tx[j], fps_tx[j + 1]) for j in range(m - 1)])
    direct = np.array([s1.hamming(fps_src[i], fps_tx[i]) for i in range(n)])
    print(f"rebind: {len(matched)}/{n} rows bound, {correct}/{n} to the right frame; Hamming median {np.median(hams):.0f}, "
          f"p99 {np.percentile(hams, 99):.0f}, max {hams.max()}; nearest-neighbour {nn_correct}/{n}; ambiguous {amb:.3f}; "
          f"consecutive-frame median {consec:.0f}; same-frame original vs transcoded: median {np.median(direct):.0f}, max {direct.max()}; {t_rebind:.2f} s")
    assert correct == n, "the reference must rebind every frame on this moving scene"

    # ---- survival of the SEI through copy paths and re-encodes, on THIS file
    tmp = OUT / "_tmp"; tmp.mkdir(exist_ok=True)
    surv = survival(DST, n, tmp)
    surv[f"libx264 transcode, {TX_RES[0]}x{TX_RES[1]}, CRF 28 (sidecar_transcoded.mp4)"] = [tx_sei, n]
    for f in tmp.iterdir(): f.unlink()
    tmp.rmdir()
    for k, v in surv.items(): print(f"  {k}: {v[0]}/{v[1]}")

    # ---- exports
    (OUT / "sidecar_rows.json").write_text(json.dumps(envs, separators=(",", ":")))
    parity = {
        "note": "Tab A: first 10 samples in decode order, raw payload bytes as returned by nanolab.sidecar.extract. "
                "Tab B: Python (nanolab.sidecar1) fingerprints of every decoded frame of sidecar_transcoded.mp4 (Y plane via ffmpeg) "
                "and the reference rebind of sidecar_rows.json against them; the page compares its first 20 JS fingerprints and its rebind.",
        "n_samples": n, "timescale": timescale,
        "samples": [{"d": d, "pts": pts[d], "raw": got[d][0].decode()} for d in range(10)],
        "survival": surv,
        "sei_bytes_per_frame": round(stats["sei_bytes_per_frame"], 1), "file_bytes": DST.stat().st_size, "clean_bytes": SRC.stat().st_size,
        "fingerprint": {
            "check_vector": CHECK_VECTOR, "transcoded": TX.name, "tx_res": list(TX_RES), "n_frames": m,
            "frames_fp": fps_tx,
            "rebind": [[j, h] for j, h in rb],
            "first20": [{"frame": j, "fp": fps_tx[j], "row": j, "bound_to": rb[j][0], "hamming": rb[j][1]} for j in range(20)],
            "summary": {"bound": len(matched), "correct": correct, "n": n, "hamming_median": float(np.median(hams)),
                        "hamming_p99": float(np.percentile(hams, 99)), "hamming_max": int(hams.max()),
                        "nearest_correct": nn_correct, "ambiguous": amb, "consecutive_median": float(consec),
                        "same_frame_median": float(np.median(direct)), "same_frame_max": int(direct.max()),
                        "window": 60, "gap": 6.0, "rebind_seconds": round(t_rebind, 3)}}}
    (OUT / "parity.json").write_text(json.dumps(parity, indent=1))
    print("wrote", OUT / "sidecar_rows.json", (OUT / "sidecar_rows.json").stat().st_size, "bytes;", OUT / "parity.json")


if __name__ == "__main__":
    main()
