#!/usr/bin/env python3
"""ladder_codec.py - carry a (down-sampled) movie *inside* the ladder, one analog value per ladder parameter.
Needs ladder_video.py, ladder_mod.py, ladder_fft.py, opencv-python, scipy.

  py ladder_codec.py encode "Top 12.mov" Top12_ladder.avi            # -> Top12_ladder.avi + Top12_ladder.avi.json (layout)
  py ladder_codec.py bench  "Top 12.mov" --frames 30                  # encode -> virtual capture chain -> decode, prints PSNR
  py ladder_codec.py decode capture.avi out.avi --meta Top12_ladder.avi.json [--ref "Top 12.mov"]

How a frame is built.  Every picture row is one ladder tick (2 periods of the S0..S6 pulse ladder, as in ladder_video).
A row carries 14 numbers x in [0,1]:  stage amplitudes A_k = Aref_k (1 + 2*depth*(x-.5))  (k=0..6)  and stage delays
d_k = dnom_k + 2*range*(x-.5) (k=0..6; d_0 is the row's time offset).  The thumbnail's pixels are dealt into those 14 slots
row after row.  The first --npilot rows carry x = .5 everywhere; the decoder measures them each frame and expresses every
other row relative to them, which cancels the chain's per-octave gain, dispersion, horizontal crop, brightness and contrast.
Rows are repeated --rowrep times so they survive vertical rescaling (HDMI->RCA, capture); black margins let the decoder
find the picture's vertical extent and hence each row's band.

Capacity is the honest limit: 14 values per data row, a few bits each (delays ~5 deg, amplitudes ~3 %), so a 1280x1024 frame
at rowrep 3 holds ~4.7k values ~ a 68x68 grayscale picture; through a 480-line capture expect roughly 40x40."""
import argparse, json, math, sys, numpy as np
from ladder_mod import peel, GT
from ladder_fft import coeff
from ladder_video import find_geometry, lines_matrix, chain, resize_area

NV = 14  # values per row for 7 stages: handled generally as 2*stages


# ---------------------------------------------------------------- shared geometry / parameter mapping
class Codec:
    def __init__(s, m):
        s.__dict__.update(m); s.S = s.stages; s.nv = 2 * s.S
        s.Aref = np.array([(math.sqrt((1 + 5 ** .5) / 2) * s.r ** ((1 + 5 ** .5) / 2)) ** k for k in range(s.S)])
        s.dnom = np.array([.25] + [(k * GT) % 1 for k in range(1, s.S)])
        s.Pper = s.W // s.nper; s.L = s.nper * s.Pper
        s.nd = math.ceil(s.tw * s.th / s.nv); s.nb = s.npilot + s.nd
    # ---- encode
    def rows_from_values(s, X):                                    # X (R, nv) in [0,1]  ->  uint8 rows (R, L)
        R = X.shape[0]; A = s.Aref[None] * (1 + 2 * s.depth * (X[:, :s.S] - .5)); d = s.dnom[None] + 2 * s.drange * (X[:, s.S:] - .5)
        u = np.zeros((R, s.S)); u[:, 0] = d[:, 0] % 1
        for k in range(1, s.S): u[:, k] = (2 * u[:, k - 1] + d[:, k]) % 1
        x = np.arange(s.L); sig = np.zeros((R, s.L))
        for k in range(s.S):
            ph = x * 2. ** k / s.Pper; dl = 2. ** k / s.Pper; uk = u[:, k:k + 1]
            I = lambda xx: np.floor(xx - uk) * s.duty + np.minimum((xx - uk) % 1, s.duty)
            sig += A[:, k:k + 1] * (I(ph[None] + dl) - I(ph[None])) / dl
        smax = s.Aref.sum() * (1 + s.depth)
        return np.round(255 * np.clip(s.lo + (s.hi - s.lo) * sig / smax, 0, 1)).astype(np.uint8)
    def encode_frame(s, thumb):                                    # thumb (th, tw) floats 0..1
        v = np.full(s.nd * s.nv, .5); v[:s.tw * s.th] = thumb.ravel()
        X = np.vstack([np.full((s.npilot, s.nv), .5), v.reshape(s.nd, s.nv)])
        rows = np.repeat(s.rows_from_values(X), s.rowrep, axis=0)
        img = np.zeros((s.H, s.W), np.uint8); r0 = s.margin; img[r0:r0 + len(rows), :s.L] = rows; return img
    # ---- decode
    def nominal_lines(s, nl):
        nn = np.arange(1, nl + 1); u = [s.dnom[0] % 1]
        for k in range(1, s.S): u.append((2 * u[-1] + s.dnom[k]) % 1)
        return sum(s.Aref[k] * coeff(nn / 2 ** k, s.duty, 1.0, u[k]) * (nn % 2 ** k == 0) for k in range(s.S))
    def equalizer(s, Cp, nl, st):
        """chain response at every harmonic, from the pilot rows (content known exactly): crop shift, blur, rescale, gain, ..."""
        m = s.nominal_lines(nl); good = np.abs(m) > .25 * np.median(np.abs(m)); n = np.arange(nl)
        Hr = np.where(good, Cp / np.where(good, m, 1), 0)
        mag = np.interp(n, n[good], np.abs(Hr[good])); ph = np.interp(n, n[good], np.unwrap(np.angle(Hr[good])))   # fill sinc-zero lines
        H = mag * np.exp(1j * ph)
        if st.get('H') is not None and st['H'].shape == H.shape: H = .6 * st['H'] + .4 * H                     # chain is static: smooth over frames
        st['H'] = H; w = np.minimum(np.abs(H) / np.abs(H).max(), 1) * np.where(good, 1, .3); return H, w
    def decode_frame(s, img, st):
        if st.get('geo') is None or st.get('n', 0) % 60 == 0:
            g = find_geometry(img, s); st['geo'] = g if g is not None else st.get('geo')
        if st.get('geo') is None: return None
        x0, L, P = st['geo']; nl = min(3 * 2 ** (s.S - 1), int(P / 2.5), int(s.fmax)); Hc = img.shape[0]; st['n'] = st.get('n', 0) + 1
        C = lines_matrix(img[:, x0:x0 + L].astype(float), P, x0, nl)
        pw = np.abs(C[:, :16]).sum(1); plat = np.median(pw[pw > .3 * np.percentile(pw, 75)]); half = .5 * plat
        on = np.where(pw >= half)[0]
        if len(on) < s.nb: return None
        i0, i1 = int(on[0]), int(on[-1])                           # sub-row picture edges: where the row power crosses half its plateau
        e0 = (i0 - 1 + .5 + (half - pw[i0 - 1]) / (pw[i0] - pw[i0 - 1])) if i0 > 0 else i0 + .5 - .5
        e1 = (i1 + .5 + (pw[i1] - half) / (pw[i1] - pw[min(i1 + 1, Hc - 1)] + 1e-12)) if i1 < Hc - 1 else i1 + .5 + .5
        bh = (e1 - e0) / s.nb
        if bh < 1.6: raise SystemExit(f"only {bh:.1f} capture rows per ladder row; raise --rowrep at encode time")
        # capture row j is (roughly) the box-average of the ladder rows it covers: solve for the ladder rows' own lines, which
        # removes the cross-talk between neighbouring rows that vertical rescaling (e.g. 1024 -> 480 lines) creates
        j0, j1 = max(0, int(math.floor(e0)) - 1), min(Hc, int(math.ceil(e1)) + 1); M = np.zeros((j1 - j0, s.nb))
        for jj in range(j0, j1):
            lo, hi = jj, jj + 1.                                      # capture row jj spans [jj, jj+1) in picture-row coordinates
            for i in range(max(0, int((lo - e0) / bh) - 1), min(s.nb, int((hi - e0) / bh) + 2)):
                M[jj - j0, i] = max(0., min(hi, e0 + (i + 1) * bh) - max(lo, e0 + i * bh))
        rows = np.linalg.lstsq(M, C[j0:j1], rcond=1e-3)[0]
        Cd = np.array(rows); H, w = s.equalizer(Cd[:s.npilot].mean(0), nl, st); Cd = Cd / H[None]
        Aa, Uu = np.zeros((s.nb, s.S)), np.zeros((s.nb, s.S))
        for i in range(s.nb):
            us, As, _ = peel(Cd[i], s.S, s.duty); Uu[i], Aa[i] = us, As
        Aa, Uu = batch_refine(Cd, s.S, s.duty, Aa, Uu, w=w)
        Dd = np.zeros_like(Uu); Dd[:, 0] = Uu[:, 0] % 1
        for k in range(1, s.S): Dd[:, k] = (Uu[:, k] - 2 * Uu[:, k - 1]) % 1
        Ap = np.median(Aa[:s.npilot], 0); z = np.exp(2j * np.pi * Dd[:s.npilot]).mean(0); Dp = np.angle(z) / (2 * np.pi)
        XA = .5 + (Aa[s.npilot:] / Ap - 1) / (2 * s.depth)
        XD = .5 + (((Dd[s.npilot:] - Dp + .5) % 1) - .5) / (2 * s.drange)
        v = np.clip(np.hstack([XA, XD]).ravel()[:s.tw * s.th], 0, 1)
        return v.reshape(s.th, s.tw)

def batch_refine(C, S, d, A0, U0, iters=14, w=None):
    """Levenberg-Marquardt on every row at once; model = sum_k pulse-train line coefficients (as ladder_fft.coeff)."""
    R, nl = C.shape; nn = np.arange(1, nl + 1); A, U = A0.copy(), U0.copy()
    w = np.ones(nl) if w is None else w; C = C * w[None]
    H = [nn / 2. ** k for k in range(S)]; mask = [(nn % 2 ** k == 0) for k in range(S)]
    base = [d * np.sinc(H[k] * d) * np.exp(-1j * np.pi * H[k] * d) * mask[k] * w for k in range(S)]
    def model(A, U, jac=False):
        m = np.zeros((R, nl), complex); JA = []; JU = []
        for k in range(S):
            e = base[k][None] * np.exp(-2j * np.pi * H[k][None] * U[:, k:k + 1]); m += A[:, k:k + 1] * e
            if jac: JA.append(e); JU.append(A[:, k:k + 1] * e * (-2j * np.pi * H[k][None]))
        return (m, np.stack(JA + JU, 2)) if jac else m
    r = C - model(A, U); cost = np.sum(np.abs(r) ** 2, 1); lam = np.full(R, 1e-3)
    for _ in range(iters):
        m, J = model(A, U, True); r = C - m
        Jr = np.concatenate([J.real, J.imag], 1); rr = np.concatenate([r.real, r.imag], 1)          # (R, 2nl, 2S)
        JtJ = np.einsum('rij,rik->rjk', Jr, Jr); Jtr = np.einsum('rij,ri->rj', Jr, rr); dg = np.einsum('rjj->rj', JtJ)
        M = JtJ + lam[:, None, None] * (dg[:, :, None] * np.eye(2 * S)[None] + 1e-12 * np.eye(2 * S)[None])
        step = np.linalg.solve(M, Jtr[..., None])[..., 0]
        A2, U2 = A + step[:, :S], U + step[:, S:]; c2 = np.sum(np.abs(C - model(A2, U2)) ** 2, 1); acc = c2 < cost
        A[acc], U[acc], cost[acc] = A2[acc], U2[acc], c2[acc]; lam = np.where(acc, lam / 3, lam * 5)
    return A, U


# ---------------------------------------------------------------- movie plumbing
def meta_from(a, W, H, aspect):
    m = dict(W=W, H=H, stages=a.stages, nper=a.nper, duty=a.duty, r=a.r, lo=a.lo, hi=a.hi, depth=a.depth, drange=a.drange,
             rowrep=a.rowrep, margin=a.margin, npilot=a.npilot, fmax=a.fmax)
    nd_max = (H - 2 * a.margin) // a.rowrep - a.npilot; cap = nd_max * 2 * a.stages
    if a.thumb == 'auto':
        tw = int(math.sqrt(cap * aspect)); th = int(tw / aspect)
        while tw * th > cap: tw -= 1; th = int(tw / aspect)
    else: tw, th = map(int, a.thumb.lower().split('x'))
    if tw * th > cap: raise SystemExit(f"thumb {tw}x{th} needs {tw*th} values, frame holds {cap}")
    m.update(tw=tw, th=th, fps=0.); return m

def thumbnail(frame, tw, th):
    import cv2
    g = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if frame.ndim == 3 else frame
    return cv2.resize(g, (tw, th), interpolation=cv2.INTER_AREA).astype(float) / 255.

def clean(t, on=True):
    import cv2
    return cv2.medianBlur((t * 255).astype(np.uint8), 3).astype(float) / 255. if on else t      # drops single mis-read slots

def psnr(a, b): e = np.mean((a - b) ** 2); return 99. if e == 0 else 10 * math.log10(1 / e)

def cmd_encode(a):
    import cv2
    cap = cv2.VideoCapture(a.src); ok, f = cap.read()
    if not ok: raise SystemExit("cannot read " + a.src)
    W, H = map(int, a.size.lower().split('x')); m = meta_from(a, W, H, f.shape[1] / f.shape[0]); fps = cap.get(cv2.CAP_PROP_FPS) or 30.; m['fps'] = fps
    cd = Codec(m); wr = cv2.VideoWriter(a.dst, cv2.VideoWriter_fourcc(*a.fourcc), fps, (W, H)); n = 0
    if not wr.isOpened(): raise SystemExit(f"cannot write {a.dst} ({a.fourcc}); try --fourcc MJPG with an .avi name")
    while ok and (not a.frames or n < a.frames):
        img = cd.encode_frame(thumbnail(f, cd.tw, cd.th)); wr.write(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)); n += 1; ok, f = cap.read()
        if n % 100 == 0: print(n, "frames", flush=True)
    wr.release(); json.dump(m, open(a.dst + ".json", "w"), indent=1)
    print(f"wrote {a.dst} + {a.dst}.json: {n} frames, {cd.tw}x{cd.th} grayscale carried in {cd.nd} data rows x {cd.nv} values, {fps:.2f} fps")
    print("audio: ffmpeg -i %s -i \"%s\" -map 0:v -map 1:a -c:v libx264 -crf 10 -c:a copy out.mp4" % (a.dst, a.src))

def cmd_decode(a):
    import cv2
    m = json.load(open(a.meta)); cd = Codec(m); st = {}
    src = int(a.source) if str(a.source).isdigit() else a.source; cap = cv2.VideoCapture(src, cv2.CAP_DSHOW) if isinstance(src, int) else cv2.VideoCapture(src)
    ref = cv2.VideoCapture(a.ref) if a.ref else None
    wr = cv2.VideoWriter(a.out, cv2.VideoWriter_fourcc(*'MJPG'), m['fps'] or 30., (cd.tw * a.scale, cd.th * a.scale)); n = 0; ps = []
    while not a.frames or n < a.frames:
        ok, f = cap.read()
        if not ok: break
        g = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(float) if f.ndim == 3 else f.astype(float); t = cd.decode_frame(g, st)
        if t is None: print(f"frame {n}: no ladder picture found"); n += 1; continue
        t = clean(t, not a.raw)
        wr.write(cv2.cvtColor(cv2.resize((t * 255).astype(np.uint8), None, fx=a.scale, fy=a.scale, interpolation=cv2.INTER_CUBIC), cv2.COLOR_GRAY2BGR))
        if ref is not None:
            ok2, rf = ref.read()
            if ok2: ps.append(psnr(t, thumbnail(rf, cd.tw, cd.th))); print(f"frame {n}: PSNR vs source thumbnail {ps[-1]:.1f} dB")
        n += 1
    wr.release(); print(f"wrote {a.out}" + (f"; mean PSNR {np.mean(ps):.1f} dB over {len(ps)} frames" if ps else ""))

def cmd_bench(a):
    import cv2
    cap = cv2.VideoCapture(a.src); ok, f = cap.read(); W, H = map(int, a.size.lower().split('x')); m = meta_from(a, W, H, f.shape[1] / f.shape[0])
    cd = Codec(m); st = {}; rng = np.random.default_rng(1); ps = []; n = 0
    print(f"{cd.tw}x{cd.th} picture, {cd.nd} data rows + {cd.npilot} pilot rows, chain: {a.capw}x{a.caph}, crop {a.cropx}, blur {a.blur}, noise {a.noise}")
    while ok and n < a.frames:
        t0 = thumbnail(f, cd.tw, cd.th); img = chain(cd.encode_frame(t0), a, rng).astype(np.uint8)
        if a.save and n == 0: cv2.imwrite("bench_frame0_capture.png", img)
        t = cd.decode_frame(img.astype(float), st)
        if t is None: print(f"frame {n}: no ladder picture found")
        else: ps.append(psnr(clean(t), t0)); print(f"frame {n}: PSNR {psnr(t, t0):.1f} dB raw, {ps[-1]:.1f} dB after 3x3 median")
        if a.save and n == 0 and t is not None: cv2.imwrite("bench_frame0_src.png", cv2.resize((t0 * 255).astype(np.uint8), None, fx=6, fy=6, interpolation=cv2.INTER_NEAREST)); cv2.imwrite("bench_frame0_decoded.png", cv2.resize((t * 255).astype(np.uint8), None, fx=6, fy=6, interpolation=cv2.INTER_NEAREST))
        n += 1; ok, f = cap.read()
    if ps: print(f"mean PSNR {np.mean(ps):.1f} dB (after median) over {len(ps)} frames (25-30 dB = clearly recognisable, 35+ = good)")

if __name__ == "__main__":
    p = argparse.ArgumentParser(); sp = p.add_subparsers(dest="cmd", required=True)
    for name, fn in (("encode", cmd_encode), ("decode", cmd_decode), ("bench", cmd_bench)):
        q = sp.add_parser(name); q.set_defaults(fn=fn)
        if name == "encode": q.add_argument("src"); q.add_argument("dst"); q.add_argument("--fourcc", default="MJPG")
        if name == "bench": q.add_argument("src")
        if name == "decode":
            q.add_argument("source"); q.add_argument("out"); q.add_argument("--meta", required=True); q.add_argument("--ref", default=None)
            q.add_argument("--scale", type=int, default=6); q.add_argument("--frames", type=int, default=0); q.add_argument("--raw", action="store_true", help="skip the 3x3 median clean-up")
        else:
            q.add_argument("--size", default="1280x1024"); q.add_argument("--thumb", default="auto"); q.add_argument("--rowrep", type=int, default=3)
            q.add_argument("--margin", type=int, default=8); q.add_argument("--npilot", type=int, default=4); q.add_argument("--nper", type=int, default=2)
            q.add_argument("--stages", type=int, default=7); q.add_argument("--duty", type=float, default=.2); q.add_argument("--r", type=float, default=.743)
            q.add_argument("--lo", type=float, default=.15); q.add_argument("--hi", type=float, default=.85)
            q.add_argument("--depth", type=float, default=.4, help="amplitude modulation depth"); q.add_argument("--drange", type=float, default=.25, help="delay swing, turns")
            q.add_argument("--fmax", type=float, default=100.); q.add_argument("--frames", type=int, default=0)
        if name == "bench":
            q.add_argument("--capw", type=int, default=720); q.add_argument("--caph", type=int, default=480); q.add_argument("--cropx", type=float, default=.03)
            q.add_argument("--blur", type=float, default=.8); q.add_argument("--noise", type=float, default=2.); q.add_argument("--contrast", type=float, default=.9)
            q.add_argument("--bright", type=float, default=0.); q.add_argument("--save", action="store_true")
    a = p.parse_args(); a.fn(a)
