#!/usr/bin/env python3
"""ladder_video.py - the HDGL-modulated octave ladder drawn as a picture, plus an analyzer for captured frames.
Needs ladder_mod.py, ladder_detect.py, ladder_fft.py alongside; pygame for `show`, opencv-python for `detect`.

  py ladder_video.py show   [--size 1280x1024] [--display 1] [--fullscreen] [--advance 6]   # put it on the VGA monitor
  py ladder_video.py save   pattern.png                                                      # one frame to a file
  py ladder_video.py bench  [--capw 720 --caph 480 --cropx .03 --blur .8 --noise 2]          # virtual chain: pattern -> capture -> analyzer
  py ladder_video.py detect --source 0                    # Roxio / any DirectShow capture device (or a PNG/MP4 path)
  py ladder_video.py detect --probe                       # list capture indices 0..5 and their frame size

Mapping.  Along a row, x is time:  one period T0 = row_width/--nper pixels, stage k = 2^k stripes per T0 (S0 is the
widest, S6 the finest), each a pulse train of duty --duty, start u_k, exactly the ladder of ladder_mod.  A *band* of
--band rows shows one ring state K; band b shows K0+b (mod kmax), so the whole ring is on screen at once and K0 steps every
--advance frames, which scrolls the bands (a waterfall).  Pixel value is linear in the signal (--gamma 1): a VGA DAC and a
composite capture are both linear in code, so the stage sum stays additive.
Analyzer: finds the active region and px-per-period from the frame itself, takes complex harmonic lines per row, splits
bands where the row vector changes, averages each band, then does the same peel + joint LSQ as the audio detector and reads K
from the measured delays.  Because d_k is invariant to horizontal shift, crop and scroll position do not matter.
Not modelled: interlace/field mixing, capture-card sharpening/AGC (set the card's brightness/contrast neutral)."""
import argparse, math, sys, numpy as np
from ladder_mod import Engine, fit_duty, peel, refine, GT

LINE_US = 52.6          # NTSC active line, used only to print rough MHz


def wh(s): w, h = s.lower().split('x'); return int(w), int(h)


# ---------------------------------------------------------------- generator
def make_templates(a, Pper):
    e = Engine(Pper, 1., a.stages, a.duty, a.nper, a.kmax, a.r, a.am); L = a.nper * Pper
    T = np.array([e.render(K * L, L)[:, a.chan] for K in range(a.kmax)])
    smax = sum(e.mag ** k for k in range(a.stages)) * (1 + abs(a.am))
    v = np.clip(a.lo + (a.hi - a.lo) * T / smax, 0, 1) ** (1 / a.gamma)
    return np.round(255 * v).astype(np.uint8)                         # (kmax, L)

def make_frame(tpl, a, W, H, K0):
    nb = H // a.band; idx = (K0 + np.arange(nb)) % a.kmax
    img = np.zeros((H, W), np.uint8); img[:nb * a.band, :tpl.shape[1]] = np.repeat(tpl[idx], a.band, axis=0)
    return img

def gen(a):
    W, H = wh(a.size); Pper = W // a.nper
    return make_templates(a, Pper), W, H

def save_image(path, img):
    try:
        import pygame; pygame.surfarray.use_arraytype  # noqa
        pygame.image.save(pygame.surfarray.make_surface(np.repeat(img.T[:, :, None], 3, 2)), path)
    except Exception:
        path = path.rsplit('.', 1)[0] + '.pgm'
        with open(path, 'wb') as f: f.write(b"P5 %d %d 255\n" % (img.shape[1], img.shape[0]) + img.tobytes())
    print("wrote", path)

def cmd_save(a):
    tpl, W, H = gen(a); save_image(a.out, make_frame(tpl, a, W, H, a.k0))

def cmd_show(a):
    import pygame
    tpl, W, H = gen(a); pygame.init()
    scr = pygame.display.set_mode((W, H), pygame.FULLSCREEN if a.fullscreen else 0, display=a.display)
    pygame.mouse.set_visible(False); clk = pygame.time.Clock(); arr = np.empty((W, H, 3), np.uint8); f = 0; paused = False
    print(f"{W}x{H}: {a.nper} periods per row, {a.band}-row bands, ring K0 steps every {a.advance} frames.  q/Esc quits, p pauses.")
    while True:
        for ev in pygame.event.get():
            if ev.type == pygame.QUIT or (ev.type == pygame.KEYDOWN and ev.key in (pygame.K_ESCAPE, pygame.K_q)): return
            if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p: paused = not paused
        K0 = (f // a.advance) % a.kmax if a.advance > 0 else a.k0
        arr[:] = make_frame(tpl, a, W, H, K0).T[:, :, None]; pygame.surfarray.blit_array(scr, arr); pygame.display.flip()
        if not paused: f += 1
        clk.tick(60)


# ---------------------------------------------------------------- analyzer
def lines_matrix(R, P, x0, nl):
    L = R.shape[1]; x = x0 + np.arange(L); n = np.arange(1, nl + 1)
    E = np.exp(-2j * np.pi * np.outer(n, x) / P)
    return (R - R.mean(1, keepdims=True)) @ E.T / L

def find_geometry(img, a):
    from scipy.ndimage import uniform_filter1d
    Hc, Wc = img.shape; sel = img[::max(1, Hc // 40)].astype(float)
    cs = uniform_filter1d(sel.std(0), 5); ok = np.where(cs > .25 * np.percentile(cs, 95))[0]
    if len(ok) < 40: return None
    x0, x1 = int(ok[0]), int(ok[-1]) + 1; Wv = x1 - x0
    seg = sel[:, x0:x1] - sel[:, x0:x1].mean(1, keepdims=True)
    r = np.fft.irfft(np.abs(np.fft.rfft(seg, 2 * Wv, axis=1)) ** 2, axis=1)[:, :Wv].mean(0)
    lo, hi = int(.9 * Wv / a.nper), min(int(Wv / 1.25), Wv - 2); i = lo + int(np.argmax(r[lo:hi]))
    p = i + .5 * (r[i - 1] - r[i + 1]) / (r[i - 1] - 2 * r[i] + r[i + 1] + 1e-12)
    n = np.arange(1, 65); best = None; rows = sel[::2]
    for P in p + np.arange(-1., 1.001, .05):                    # fine period: harmonic lines are sharpest at the right P
        L = min(int(P), Wv); C = lines_matrix(rows[:, x0:x0 + L], P, x0, 64)
        E = np.sum(np.abs(C) ** 2 * n)
        if best is None or E > best[0]: best = (E, P)
    P = best[1]; return x0, min(int(P), Wv), P         # analysis window = exactly one period

def analyze_frame(img, a, st, step=1):
    if getattr(a, 'strip', 0):                                  # ladder strip inside a movie frame: analyse only those rows
        img = img[-a.strip:] if a.where == 'bottom' else img[:a.strip]
    g = find_geometry(img, a)
    if g is None: print("no pattern found (no columns with structure)"); return None
    x0, L, P = g; nl = min(3 * 2 ** (a.stages - 1), int(P / 2.5), int(a.fmax))
    if nl < 2 ** (a.stages - 1): print(f"period {P:.1f}px is too short for {a.stages} stages (need >= {2.5 * 2 ** (a.stages - 1):.0f})"); return None
    Hc = img.shape[0]; R = img[:, x0:x0 + L].astype(float); C = lines_matrix(R, P, x0, nl)
    pw = np.abs(C[:, :16]).sum(1); valid = pw > .3 * np.median(pw)
    d = np.linalg.norm(C[1:, :16] - C[:-1, :16], axis=1); thr = max(5 * np.median(d), .05 * np.percentile(d, 95)); tr = np.zeros(Hc, bool)
    tr[:-1] |= d > thr; tr[1:] |= d > thr
    good_rows = valid & ~tr; bands = []; r0 = None
    for r in range(Hc + 1):
        if r < Hc and good_rows[r]: r0 = r if r0 is None else r0
        elif r0 is not None:
            if r - r0 >= a.minrows: bands.append((r0, r - 1))
            r0 = None
    sg = 1 if a.chan == 0 else -1; e = Engine(1, 1., a.stages, a.duty, 1, a.kmax, a.r, a.am); out = []
    for (r0, r1) in bands:
        c = C[r0:r1 + 1].mean(0)
        if st.get('duty') is None:
            st['duty'] = fit_duty(c, a.stages)
            if not .03 < st['duty'] < .58:                       # pulse-width fit ran to its limit: this is not a pulse ladder
                print("no ladder pattern in this frame (pulse-width fit ran to its limit; ordinary picture content?)"); st['duty'] = None; return None
        us, As, rr = peel(c, a.stages, st['duty']); us, As = refine(c, a.stages, st['duty'], us, As)
        dm = np.array([(us[k] - 2 * us[k - 1]) % 1 for k in range(1, a.stages)])
        errs = np.array([math.sqrt(np.mean((((dm - np.array([(sg * (K + k) * GT) % 1 for k in range(1, a.stages)]) + .5) % 1) - .5) ** 2)) * 360
                         for K in range(a.kmax)])
        out.append(dict(rows=(r0, r1), errs=errs, As=As))
    nb = len(out)
    if nb == 0: print("frame: no bands found"); return None
    # ring prior: bands run K0, K0+1, ... down the picture (spacing measured from band centres). K and K+-13 differ by
    # only 12 deg (K+-8: 20 deg) because 13*(2-phi) and 8*(2-phi) are nearly whole turns, so one band alone is ambiguous.
    cen = np.array([(b['rows'][0] + b['rows'][1]) / 2 for b in out]); med = np.median(np.diff(cen)) if nb > 2 else 1.; best = None
    for sp_ in med * np.linspace(.85, 1.15, 121):               # band pitch is not an integer number of rows after scaling: fit it too
        ix = np.round((cen - cen[0]) / sp_).astype(int)
        for K0_ in range(a.kmax):
            c_ = sum(b['errs'][(K0_ + i) % a.kmax] ** 2 for b, i in zip(out, ix))
            if best is None or c_ < best[0]: best = (c_, sp_, K0_, ix)
    _, sp, K0, idx = best
    for b, i in zip(out, idx):
        b['K'] = (K0 + i) % a.kmax; b['err'] = b['errs'][b['K']]; b['raw'] = int(np.argmin(b['errs'])); b['ok'] = b['err'] < a.rms_ok
        p = e.tick(b['K']); As = b['As']
        b['gains'] = [(As[k] / As[0]) / (p['amp'][k] / p['amp'][0]) if As[0] > 0 else float('nan') for k in range(1, a.stages)]
    okc = sum(b['ok'] for b in out); agree = sum(b['raw'] == b['K'] for b in out)
    fr = ""
    if st.get('K0') is not None:                                # ring offset advances one per frame: a counter that exposes dropped frames
        dk = (K0 - st['K0']) % a.kmax; fr = "  frame step +%d %s" % (dk, "ok" if dk == step % a.kmax else f"(expected +{step % a.kmax}: frames dropped/repeated?)")
    st['K0'] = K0
    G = np.array([b['gains'] for b in out if b['ok']]) if okc else np.zeros((0, a.stages - 1))
    verdict = "LADDER" if okc >= max(2, nb // 2) else "NO LADDER (fits no better than chance)"
    print(f"{verdict} | frame: pattern x={x0}..{x0 + L} ({P:.2f} px per period)  bands {nb} (~{sp:.1f} rows each)  top band K={K0}  "
          f"fit within {a.rms_ok:.0f} deg: {okc}/{nb}  single-band K agrees with ring order: {agree}/{nb}  duty {st['duty']:.3f}{fr}")
    if len(G):
        gm = np.median(G, 0); f0 = img.shape[1] / (P * LINE_US * 1e-6)      # Hz if the frame width spans the active line
        print("  gain per octave (S1..S%d vs S0): " % (a.stages - 1) + " ".join(f"{x:5.2f}" for x in gm)
              + f"   ~{f0*2/1e6:.2f}..{f0*2**(a.stages-1)/1e6:.2f} MHz if the picture spans the {LINE_US} us active line")
    if a.v:
        for b in out: print(f"   rows {b['rows'][0]:3d}-{b['rows'][1]:3d}  K={b['K']:2d}  {'ok  ' if b['ok'] else 'weak'} d_k rms err {b['err']:5.1f} deg  (single-band guess K={b['raw']})")
    return out


# ---------------------------------------------------------------- virtual capture chain
def resize_area(arr, newH, newW):
    def ax(x, n_new):
        n = x.shape[0]; cs = np.vstack([np.zeros((1,) + x.shape[1:]), np.cumsum(x, 0)]); ed = np.linspace(0, n, n_new + 1)
        def f(p): i = np.minimum(np.floor(p).astype(int), n - 1); fr = (p - i)[:, None]; return cs[i] * (1 - fr) + cs[i + 1] * fr
        return (f(ed[1:]) - f(ed[:-1])) / (ed[1:] - ed[:-1])[:, None]
    return ax(ax(arr.astype(float), newH).T, newW).T

def chain(img, a, rng):
    from scipy.ndimage import gaussian_filter1d
    W = img.shape[1]; cx = int(a.cropx * W); x = img[:, cx:W - cx].astype(float)
    x = resize_area(x, a.caph, a.capw)
    if a.blur > 0: x = gaussian_filter1d(x, a.blur, axis=1)
    x = a.contrast * (x - 128) + 128 + a.bright + a.noise * rng.standard_normal(x.shape)
    return np.clip(np.round(x), 0, 255)

def cmd_bench(a):
    tpl, W, H = gen(a); rng = np.random.default_rng(1); st = {}
    for f in range(a.frames):
        print(f"--- frame {f}: ring offset K0={f * a.stepper % a.kmax}")
        analyze_frame(chain(make_frame(tpl, a, W, H, f * a.stepper % a.kmax), a, rng), a, st)


# ---------------------------------------------------------------- stamp the ladder onto a movie
def cmd_overlay(a):
    try: import cv2
    except Exception: raise SystemExit("pip install opencv-python")
    cap = cv2.VideoCapture(a.src); ok, f = cap.read()
    if not ok: raise SystemExit("cannot read " + a.src)
    H, W = f.shape[:2]; fps = cap.get(cv2.CAP_PROP_FPS) or 30.; a.size = f"{W}x{H}"; Pper = W // a.nper
    tpl = make_templates(a, Pper); L = tpl.shape[1]; sh = a.bands * a.band
    wr = cv2.VideoWriter(a.dst, cv2.VideoWriter_fourcc(*a.fourcc), fps, (W, H))
    if not wr.isOpened(): raise SystemExit(f"cannot write {a.dst} with codec {a.fourcc}; try --fourcc MJPG and an .avi name")
    n = 0
    while ok:
        K0 = n % a.kmax; idx = (K0 + np.arange(a.bands)) % a.kmax; st = np.repeat(tpl[idx], a.band, axis=0)
        y0 = H - sh - a.margin if a.where == 'bottom' else a.margin
        f[y0:y0 + sh, :L] = st[:, :, None]; wr.write(f); n += 1; ok, f = cap.read()
        if n % 300 == 0: print(n, "frames", flush=True)
    wr.release(); print(f"wrote {a.dst}: {n} frames, strip = {sh} rows at the {a.where} ({a.bands} bands of {a.band}), ring offset = frame number mod {a.kmax}")
    print(f"detect with:  py ladder_video.py detect --source <capture> --strip {sh + a.margin} --where {a.where} --every 1")
    print("audio is not carried by OpenCV: mux it back, e.g.  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))


# ---------------------------------------------------------------- capture input
def cmd_detect(a):
    try: import cv2
    except Exception: raise SystemExit("pip install opencv-python")
    if a.probe:
        for i in range(6):
            c = cv2.VideoCapture(i, cv2.CAP_DSHOW); ok, f = c.read()
            print(i, f"{f.shape[1]}x{f.shape[0]}" if ok else "-"); c.release()
        return
    st = {}; src = int(a.source) if str(a.source).isdigit() else a.source
    if isinstance(src, int):
        cap = cv2.VideoCapture(src, cv2.CAP_DSHOW); cap.set(cv2.CAP_PROP_FRAME_WIDTH, 720); cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        for _ in range(10): cap.read()
    else: cap = cv2.VideoCapture(src)
    n = i = 0
    while n < a.frames:
        ok, f = cap.read()
        if not ok: break
        i += 1
        if (i - 1) % a.every: continue
        g = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(float) if f.ndim == 3 else f.astype(float)
        analyze_frame(g, a, st, a.every); n += 1

if __name__ == "__main__":
    p = argparse.ArgumentParser(); sp = p.add_subparsers(dest="cmd", required=True)
    for name, fn in (("show", cmd_show), ("save", cmd_save), ("bench", cmd_bench), ("detect", cmd_detect), ("overlay", cmd_overlay)):
        q = sp.add_parser(name); q.set_defaults(fn=fn)
        if name == "save": q.add_argument("out"); q.add_argument("--k0", type=int, default=0)
        if name == "overlay":
            q.add_argument("src"); q.add_argument("dst"); q.add_argument("--bands", type=int, default=7, help="ring states shown in the strip")
            q.add_argument("--where", default="bottom", choices=["bottom", "top"]); q.add_argument("--margin", type=int, default=0, help="rows between strip and frame edge")
            q.add_argument("--fourcc", default="MJPG")
        q.add_argument("--size", default="1280x1024"); q.add_argument("--nper", type=int, default=2, help="periods per row")
        q.add_argument("--band", type=int, default=16, help="rows per ring state (use 8 for overlay strips)"); q.add_argument("--stages", type=int, default=7)
        q.add_argument("--duty", type=float, default=.2); q.add_argument("--kmax", type=int, default=21)
        q.add_argument("--r", type=float, default=.743); q.add_argument("--am", type=float, default=0.)
        q.add_argument("--chan", type=int, default=0, help="0=S+, 1=S-"); q.add_argument("--lo", type=float, default=.15); q.add_argument("--hi", type=float, default=.85)
        q.add_argument("--gamma", type=float, default=1.); q.add_argument("--fmax", type=float, default=100.)
        q.add_argument("--rms-ok", dest="rms_ok", type=float, default=20.); q.add_argument("--minrows", type=int, default=2); q.add_argument("-v", dest="v", action="store_true")
        if name == "show":
            q.add_argument("--display", type=int, default=0); q.add_argument("--fullscreen", action="store_true")
            q.add_argument("--advance", type=int, default=6, help="frames per ring step; 0 = hold K0"); q.add_argument("--k0", 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("--frames", type=int, default=3); q.add_argument("--stepper", type=int, default=1)
        if name == "detect":
            q.add_argument("--source", default="0"); q.add_argument("--probe", action="store_true"); q.add_argument("--frames", type=int, default=5)
            q.add_argument("--strip", type=int, default=0, help="analyse only this many rows (ladder strip inside a movie)"); q.add_argument("--where", default="bottom", choices=["bottom", "top"])
            q.add_argument("--every", type=int, default=1, help="analyse every Nth frame")
    a = p.parse_args(); a.fn(a)
