#!/usr/bin/env python3
"""ladder_detect.py - virtual bench + blind detector for the HDGL-modulated octave ladder (needs ladder_mod.py, ladder_fft.py).

  python3 ladder_detect.py bench  [--f0 100 --hp 30 --lp 12000 --noise .02 --ppm 50 --lat .0137]   # tx -> chain model -> detector
  python3 ladder_detect.py detect rec.wav [--chan 0]            # detector on a capture of the VCR audio output
  python3 ladder_detect.py live   [--dev N] [--chan 0]          # detector on the sound-card input (needs sounddevice)
  (transmit side: python3 ladder_mod.py play --f0 100 --fs 48000 ...  ->  Archer modulator audio/video input)

Blind: it is told only the nominal f0, hold, kmax, stages.  It finds, in this order
  1. f0   - autocorrelation peak near T0 (absorbs sound-card / tx clock offset)
  2. tick - folds the period-to-period change of the first 16 harmonics modulo `hold` (parameters step once per tick)
  3. K    - ring position, read from the measured delays: d_k = frac((K+k)(2-phi)) differs for every K, so the delay
            vector itself names the ring state. Then K must advance (K+1) mod kmax every tick: that is the lock check.
Per tick it also prints the chain's gain per octave: measured A_k/A_0 over the transmitted ratio = your RF/VCR/audio
response at f0*2^k relative to f0 (leave --hpf at 0 for hardware so nothing is divided out).
Assumes the chain is roughly flat over the lines used (<= --fmax); strong tilt biases d_k. Audio path only (RF audio
subcarrier -> VCR audio out); a video-line path would need a different front end."""
import argparse, math, sys, time, wave, numpy as np
from ladder_mod import Engine, window_lines, fit_duty, peel, refine, GT


def devarg(v):
    """--dev 14 must reach sounddevice as an int (a string means a name search)"""
    return int(v) if v is not None and str(v).lstrip('-').isdigit() else v


# ---------------------------------------------------------------- chain model
class Bench:
    """modulator -> RF -> VCR audio out -> capture: 1st-order HPF (AC coupling) + LPF, gain, white noise."""
    def __init__(s, fs, hp=30., lp=12000., gain=.3, noise=.02, seed=1):
        from scipy.signal import lfilter
        s.lf, s.gain, s.noise, s.rng = lfilter, gain, noise, np.random.default_rng(seed)
        k = math.tan(math.pi * hp / fs) if hp > 0 else None; q = math.tan(math.pi * lp / fs) if lp > 0 else None
        s.stages = []
        if k: s.stages.append((np.array([1., -1.]) / (1 + k), np.array([1., (k - 1) / (k + 1)])))
        if q: s.stages.append((np.array([q, q]) / (1 + q), np.array([1., (q - 1) / (q + 1)])))
        s.zi = [np.zeros(1) for _ in s.stages]
    def __call__(s, x):
        for i, (b, a) in enumerate(s.stages): x, s.zi[i] = s.lf(b, a, x, zi=s.zi[i])
        return s.gain * x + s.noise * s.rng.standard_normal(len(x))


# ---------------------------------------------------------------- blind detector
def decode_K(dm, kmax, S, sg):
    errs = []
    for K in range(kmax):
        e = np.array([(sg * (K + k) * GT) % 1 for k in range(1, S)])
        dd = np.abs(((np.array(dm[1:]) - e + .5) % 1) - .5)
        errs.append(math.sqrt(np.mean(dd ** 2)) * 360)
    o = np.argsort(errs); return int(o[0]), errs[o[0]], errs[o[1]]

class Detector:
    def __init__(s, eng, chan=0, hp=0., fmax=8000., tol=.01, acq=4, rms_ok=20., verbose=False, out=print, lp=0.):
        s.e, s.sg, s.hp, s.lp, s.tol, s.acq, s.rms_ok, s.v, s.out = eng, (1 if chan == 0 else -1), hp, lp, tol, acq, rms_ok, verbose, out
        s.nl = min(3 * 2 ** (eng.S - 1), int(fmax / eng.f0))
        if s.nl < 2 ** (eng.S - 1): raise SystemExit(f"--fmax {fmax} too low: need lines up to {2**(eng.S-1)}*f0")
        if eng.hold < 3: raise SystemExit("--hold must be >= 3 for blind tick detection")
        s.nper = eng.hold - 2; s.reset()
    def reset(s):
        s.buf = np.zeros(0); s.base = 0; s.mode = 'acq'; s.d = None; s.Kprev = None; s.bad = 0; s.n = 0
    def feed(s, x):
        s.buf = np.concatenate([s.buf, x]); fs = s.e.fs
        if s.mode == 'acq' and len(s.buf) >= s.acq * s.e.hold * fs / s.e.f0: s.acquire()
        while s.mode == 'trk':
            s0 = int(round(s.anchor + s.n * s.e.hold * s.Tf)); L = int(round(s.nper * s.Tf))
            if s.base + len(s.buf) < s0 + L: break
            s.decode(s0, s.buf[s0 - s.base: s0 - s.base + L]); s.n += 1
            if s.mode == 'trk':
                cut = max(0, min(len(s.buf), int(round(s.anchor + s.n * s.e.hold * s.Tf)) - s.base)); s.buf = s.buf[cut:]; s.base += cut
    def acquire(s):
        fs, f0 = s.e.fs, s.e.f0; x = s.buf - s.buf.mean(); N = len(x)
        F = np.fft.rfft(x, 2 * N); r = np.fft.irfft(np.abs(F) ** 2)[:N]; lag0 = fs / f0
        lo, hi = int(lag0 * (1 - s.tol)), int(lag0 * (1 + s.tol)) + 2; i = lo + int(np.argmax(r[lo:hi]))
        if r[i] < .4 * r[0] or i in (lo, hi - 1): self_msg = "no periodicity at nominal f0"; s.out(f"acq: {self_msg}, waiting"); s.buf = s.buf[len(s.buf)//2:]; s.base += 0; return
        a, b, c = r[i - 1], r[i], r[i + 1]; lag = i + .5 * (a - c) / (a - 2 * b + c)
        s.Tf = lag; s.f0 = fs / lag; M = int(N / lag) - 1
        C = [window_lines(x[int(round(m * lag)): int(round(m * lag)) + int(round(lag))], fs, int(round(m * lag)), s.f0, 16, 0.) for m in range(M)]
        g = np.array([0.] + [np.linalg.norm(C[m] - C[m - 1]) for m in range(1, M)]); acc = np.zeros(s.e.hold)
        for m in range(1, M): acc[m % s.e.hold] += g[m]
        p = int(np.argmax(acc)); m0 = p + 1
        while m0 < 1: m0 += s.e.hold
        s.anchor = s.base + m0 * lag; s.n = 0; s.buf = s.buf[int(round(m0 * lag)):]; s.base += int(round(m0 * lag)); s.anchor = s.base
        s.mode = 'trk'; s.out(f"acq: f0={s.f0:.4f} Hz (nominal {f0}, {1e6*(s.f0/f0-1):+.0f} ppm), tick phase = period {p} of {s.e.hold}, windows {s.nper} periods")
    def lines(s, w, s0, nl=None):
        nl = nl or s.nl; c = window_lines(w, s.e.fs, s0, s.f0, nl, s.hp)
        if s.lp > 0: c = c * (1 + 1j * s.f0 * np.arange(1, nl + 1) / s.lp)      # undo 1st-order low-pass
        return c
    def track_f0(s, w, s0):
        """clock drift: a pure f0 error makes line n rotate 2*pi*n*df*dT between the first and last period of the window"""
        if s.nper < 2: return
        L = int(round(s.Tf)); a = s.lines(w[:L], s0, 64); b0 = int(round((s.nper - 1) * s.Tf)); b = s.lines(w[b0:b0 + L], s0 + b0, 64)
        n = np.arange(1, 65); wt = np.abs(a) * np.abs(b); dT = b0 / s.e.fs
        if wt.sum() <= 0: return
        df = np.sum(wt * n * np.angle(b / a)) / (2 * np.pi * dT * np.sum(wt * n ** 2))
        nxt = s.anchor + (s.n + 1) * s.e.hold * s.Tf
        s.f0 += .3 * df; s.Tf = s.e.fs / s.f0; s.anchor = nxt - (s.n + 1) * s.e.hold * s.Tf
    def decode(s, s0, w):
        c = s.lines(w, s0)
        if s.d is None: s.d = fit_duty(c, s.e.S)
        us, As, rr = peel(c, s.e.S, s.d); us, As = refine(c, s.e.S, s.d, us, As)
        dm = [float('nan')] + [(us[k] - 2 * us[k - 1]) % 1 for k in range(1, s.e.S)]
        K, err, err2 = decode_K(dm, s.e.kmax, s.e.S, s.sg)
        seq = s.Kprev is None or K == (s.Kprev + 1) % s.e.kmax; good = err < s.rms_ok and err2 > 1.5 * err
        s.bad = 0 if good else s.bad + 1
        flag = "LOCK" if good and seq else ("jump" if good else "weak")
        p = s.e.tick(K)  # expected amplitude ratios depend only on stage index
        gains = [(As[k] / As[0]) / (p['amp'][k] / p['amp'][0]) for k in range(1, s.e.S)] if As[0] > 0 else [float('nan')] * (s.e.S - 1)
        s.out(f"tick {s.n:4d} {flag:4s} K={K:2d} N={(-1)**K:+d} d_k rms err {err:5.1f} deg (next best {err2:5.1f})  duty={s.d:.3f}  "
              f"gain/oct " + " ".join(f"{g:5.2f}" for g in gains))
        if good: s.Kprev = K
        s.track_f0(w, s0)
        if s.bad >= 5: s.out("lost lock -> re-acquiring"); s.reset()


# ---------------------------------------------------------------- front ends
def mk_engine(a): return Engine(a.fs, a.f0, a.stages, a.duty, a.hold, a.kmax, a.r, a.am)

def cmd_bench(a):
    tx = Engine(a.fs * (1 + a.ppm * 1e-6), a.f0, a.stages, a.duty, a.hold, a.kmax, a.r, a.am)   # tx clock differs from rx clock
    ch = Bench(a.fs, a.hp, a.lp, a.gain, a.noise); det = Detector(mk_engine(a), a.chan, a.hp if a.hpf is None else a.hpf, a.fmax, verbose=a.v, lp=a.lp if a.lpf is None else a.lpf)
    n0 = int(a.lat * a.fs); blk = a.fs // 20; total = int(a.secs * a.fs); t_start = time.time(); pos = 0
    sg = a.chan
    while pos < total:
        y = tx.render(n0 + pos, blk)[:, sg]; det.feed(ch(y)); pos += blk
        if a.speed > 0:
            lag = pos / a.fs / a.speed - (time.time() - t_start)
            if lag > 0: time.sleep(lag)

def cmd_detect(a):
    w = wave.open(a.file); a.fs = w.getframerate(); chn = w.getnchannels()
    x = np.frombuffer(w.readframes(w.getnframes()), '<i2').astype(float).reshape(-1, chn)[:, min(a.chan, chn - 1)]
    det = Detector(mk_engine(a), a.chan, a.hpf or 0., a.fmax, verbose=a.v, lp=a.lpf or 0.)
    for i in range(0, len(x), a.fs // 10): det.feed(x[i:i + a.fs // 10])

def cmd_live(a):
    import queue
    try: import sounddevice as sd
    except Exception as ex: raise SystemExit(f"sounddevice unavailable ({ex}); use detect on a recorded WAV")
    q = queue.Queue(); det = Detector(mk_engine(a), a.chan, a.hpf or 0., a.fmax, verbose=a.v, lp=a.lpf or 0.)
    def cb(inp, frames, ti, st): q.put(inp[:, min(a.chan, inp.shape[1] - 1)].astype(float).copy())
    with sd.InputStream(samplerate=a.fs, channels=2, device=devarg(a.dev), callback=cb):
        while True: det.feed(q.get())

if __name__ == "__main__":
    p = argparse.ArgumentParser(); sp = p.add_subparsers(dest="cmd", required=True)
    for name, f in (("bench", cmd_bench), ("detect", cmd_detect), ("live", cmd_live)):
        q = sp.add_parser(name); q.set_defaults(fn=f)
        if name == "detect": q.add_argument("file")
        q.add_argument("--fs", type=int, default=48000); q.add_argument("--f0", type=float, default=100., help="bench f0 (the ladder is scale-invariant; 0.979 for earth)")
        q.add_argument("--stages", type=int, default=7); q.add_argument("--duty", type=float, default=.2)
        q.add_argument("--hold", type=int, default=4); 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("--hpf", type=float, default=None, help="AC-coupling corner (Hz) to divide out; bench defaults to --hp, else 0")
        q.add_argument("--lpf", type=float, default=None, help="1st-order low-pass corner (Hz) to divide out; bench defaults to --lp, else 0")
        q.add_argument("--fmax", type=float, default=8000., help="highest line used (Hz)"); q.add_argument("-v", dest="v", action="store_true")
        q.add_argument("--dev", default=None)
        if name == "bench":
            q.add_argument("--hp", type=float, default=30., help="chain AC-coupling corner (Hz)"); q.add_argument("--lp", type=float, default=12000., help="chain low-pass (Hz)")
            q.add_argument("--gain", type=float, default=.3); q.add_argument("--noise", type=float, default=.02)
            q.add_argument("--ppm", type=float, default=50., help="tx vs rx clock error"); q.add_argument("--lat", type=float, default=.0137, help="rx joins this late (s)")
            q.add_argument("--secs", type=float, default=4.); q.add_argument("--speed", type=float, default=0.)
    a = p.parse_args(); a.fn(a)
