#!/usr/bin/env python3
"""ladder_mod.py - drive the octave ladder (S0..S6 at f0*2^k) from the HDGL / Spiral8 substrate, in realtime,
and track it with a windowed version of ladder_fft's peeling analyzer.  Needs ladder_fft.py alongside.

  python3 ladder_mod.py loop  --speed 1  --noise .02 --hpf 10     # tx -> channel model -> tracker, no hardware
  python3 ladder_mod.py play  [--dev N]                           # realtime stereo out (needs sounddevice)
  python3 ladder_mod.py live  [--dev N] [--chan 0]                # realtime tracker on sound-card input
  python3 ladder_mod.py synth out.wav --secs 120                  # same signal to a stereo 16-bit WAV
  python3 ladder_mod.py track out.wav [--chan 0]                  # tracker on a recording

Modulation law (all from the Fibonacci ring (A,B) of the forum posts; Omega = phi):
  ring tick (A,B)->(B,A+B) every --hold periods of T0;  K = FibIndex(A,B);  P = A*phi+(B-A) = phi^K;
  N = B^2-A*B-A^2 = (-1)^K  (Cassini clock);  G = 2*pi*(2-phi) golden angle.
  delay of stage k      d_k = frac((K+k)*(2-phi))           (golden-angle orientation ANGLE=K*G, stepped per octave)
  stage start           u_k = (2*u_{k-1} + d_k) mod 1       (u_0 = d_0; exactly ladder_fft's delay convention)
  amplitude of stage k  |Psi_k| = (sqrt(phi)*r^phi)^k * (1 + am*N)   (Psi_{k+1} = sqrt(phi) r^phi e^{i2pi phi} Psi_k)
  strands               S+ uses +d_k, S- uses -d_k  (conjugate rotations, shared axis)  -> stereo ch0 / ch1
Note e^{i 2 pi phi} = e^{-iG}: Psi's phase step per octave is the reversed golden angle, so it adds nothing beyond d_k.
The ring is wrapped back to (0,1) after --kmax ticks so K stays bounded (the one deviation from 'counterless').
d_k (k>=1) is invariant to a common time offset between tx and rx; u_0 is not."""
import argparse, math, sys, time, wave, numpy as np
from ladder_fft import PHI, coeff, hpf

GT = 2 - PHI                                  # golden angle in turns = phi^-2


# ---------------------------------------------------------------- HDGL ring
def fib_index(A, B):
    if B == 1: return 0 if A == 0 else 1
    return round(math.log(B * 5 ** .5) / math.log(PHI)) - 1

def ring_at(steps):
    A, B = 0, 1
    for _ in range(steps): A, B = B, A + B
    return A, B

class Engine:
    """Stateless-by-tick modulation source; render(n0, n) -> (n,2) float array for sample indices n0..n0+n-1."""
    def __init__(s, fs=8000, f0=.979, stages=7, duty=.2, hold=4, kmax=21, r=.743, am=0., amp=1.):
        s.fs, s.f0, s.S, s.duty, s.hold, s.kmax, s.am, s.amp = fs, f0, stages, duty, hold, kmax, am, amp
        s.W = hold / f0; s.mag = math.sqrt(PHI) * r ** PHI; s._c = {}
    def tick(s, j):
        if j in s._c: return s._c[j]
        A, B = ring_at(j % s.kmax); K = fib_index(A, B); N = B*B - A*B - A*A
        d = [((K + k) * GT) % 1 for k in range(s.S)]
        def starts(sg):
            u = [(sg * d[0]) % 1]
            for k in range(1, s.S): u.append((2 * u[-1] + sg * d[k]) % 1)
            return u
        amp = [s.amp * s.mag ** k * (1 + s.am * N) for k in range(s.S)]
        p = dict(K=K, N=N, P=A * PHI + (B - A), d=d, amp=amp, u=(starts(1), starts(-1)))
        s._c[j] = p; return p
    def bounds(s, j): return math.ceil(j * s.W * s.fs), math.ceil((j + 1) * s.W * s.fs)
    def render(s, n0, n):
        out = np.zeros((n, 2)); pos = 0
        while pos < n:
            i = n0 + pos; j = int(i / (s.W * s.fs))
            while s.bounds(j)[1] <= i: j += 1
            seg = min(n - pos, s.bounds(j)[1] - i); p = s.tick(j)
            t = (i + np.arange(seg)) / s.fs
            for k in range(s.S):
                fk = s.f0 * 2 ** k; ph = t * fk; dl = fk / s.fs
                for ch in (0, 1):
                    u = p['u'][ch][k]      # area-averaged (integrate-and-dump) pulse: exact coverage of each sample interval
                    I = lambda x: np.floor(x - u) * s.duty + np.minimum((x - u) % 1, s.duty)
                    out[pos:pos+seg, ch] += p['amp'][k] * (I(ph + dl) - I(ph)) / dl
            pos += seg
        return out            # unipolar pulses (DC included); ladder_fft/tracker ignore DC


# ---------------------------------------------------------------- channel model (loop mode)
class Channel:
    def __init__(s, fs, hp=0., noise=0., seed=1):
        s.hp, s.noise, s.rng = hp, noise, np.random.default_rng(seed); s.zi = None
        if hp > 0:
            from scipy.signal import lfilter
            k = math.tan(math.pi * hp / fs); s.b = np.array([1., -1.]) / (1 + k); s.a = np.array([1., (k - 1) / (k + 1)])
            s.lf = lfilter
    def __call__(s, x):
        if s.hp > 0:
            if s.zi is None: s.zi = np.zeros((1, x.shape[1])); s.dc0 = None
            y, s.zi = s.lf(s.b, s.a, x, axis=0, zi=s.zi)
            x = y
        return x + s.noise * s.rng.standard_normal(x.shape)


# ---------------------------------------------------------------- windowed peeling analyzer
def window_lines(x, fs, s0, f0, nmax, hp):
    t = (s0 + np.arange(len(x))) / fs
    c = np.array([np.mean(x * np.exp(-2j * np.pi * n * f0 * t)) for n in range(1, nmax + 1)])
    return c / np.array([hpf(n * f0, hp) for n in range(1, nmax + 1)])

def fit_duty(c, S):
    odd = np.arange(1, 2 ** (S - 1) + 1, 2); best = None
    for d in np.linspace(.02, .6, 291):
        s1 = coeff(1, d, 1.0, 0.0); u = (-np.angle(c[0] / s1) / (2 * np.pi)) % 1; A = abs(c[0]) / abs(s1)
        r = np.sum(np.abs(c[odd - 1] - coeff(odd, d, A, u)) ** 2)
        if best is None or r < best[0]: best = (r, d)
    return best[1]

def peel(c, S, d):
    """closed-form peel with known duty: stage k from line 2^k after subtracting stages j<k."""
    nn = np.arange(1, len(c) + 1); us, As = [], []
    s1 = coeff(1, d, 1.0, 0.0); resid = c.copy()
    for k in range(S):
        z = resid[2 ** k - 1]; A = abs(z) / abs(s1); u = (-np.angle(z / s1) / (2 * np.pi)) % 1
        us.append(u); As.append(A)
        resid = resid - coeff(nn / 2 ** k, d, A, u) * (nn % 2 ** k == 0)
    return us, As, np.sum(np.abs(resid) ** 2) / np.sum(np.abs(c) ** 2)

def refine(c, S, d, us, As):
    """joint least squares over all lines (stage-0 phase error is multiplied by 2^k at line 2^k, so sequential
    peeling is noise-limited at the top stages; using every harmonic of every stage fixes that). Needs scipy."""
    try: from scipy.optimize import least_squares
    except Exception: return us, As
    nn = np.arange(1, len(c) + 1)
    def model(x):
        m = np.zeros(len(c), complex)
        for k in range(S): m += coeff(nn / 2 ** k, d, x[k], x[S + k]) * (nn % 2 ** k == 0)
        return m
    f = lambda x: np.concatenate([(c - model(x)).real, (c - model(x)).imag])
    x = least_squares(f, np.array(list(As) + list(us)), method='lm').x
    return [v % 1 for v in x[S:]], list(x[:S])

class Tracker:
    """feed() raw samples of one strand; yields one result per ring tick as its window completes."""
    def __init__(s, eng, chan=0, hp=0., duty=None, guard=.5, t0=0., j0=0, verbose=False, refine=True):
        s.e, s.chan, s.hp, s.d, s.guard, s.off, s.j, s.v = eng, chan, hp, duty, guard, round(t0 * eng.fs), j0, verbose
        s.refine = refine
        s.nper = eng.hold - math.ceil(2 * guard)
        if s.nper < 1: raise SystemExit("--hold too small for --guard")
        s.L = round(s.nper * eng.fs / eng.f0); s.buf = np.zeros(0); s.base = 0
    def feed(s, x):
        s.buf = np.concatenate([s.buf, x]); res = []
        while True:
            s0 = math.ceil(s.e.bounds(s.j)[0] + s.guard * s.e.fs / s.e.f0) + s.off
            if s.base + len(s.buf) < s0 + s.L: break
            w = s.buf[s0 - s.base: s0 - s.base + s.L]
            c = window_lines(w, s.e.fs, s0, s.e.f0, 3 * 2 ** (s.e.S - 1), s.hp)
            if s.d is None: s.d = fit_duty(c, s.e.S)
            us, As, rr = peel(c, s.e.S, s.d)
            if s.refine: us, As = refine(c, s.e.S, s.d, us, As)
            res.append(s.report(us, As, rr))
            s.j += 1; nxt = math.ceil(s.e.bounds(s.j)[0] + s.guard * s.e.fs / s.e.f0) + s.off
            cut = min(max(nxt - s.base, 0), len(s.buf))      # drop only samples we actually hold
            s.buf = s.buf[cut:]; s.base += cut
        return res
    def report(s, us, As, rr):
        p = s.e.tick(s.j); sg = 1 if s.chan == 0 else -1; S = s.e.S
        dm = [float('nan')] + [(us[k] - 2 * us[k - 1]) % 1 for k in range(1, S)]
        de = [(sg * x) % 1 for x in p['d']]
        derr = [abs(((dm[k] - de[k] + .5) % 1) - .5) * 360 for k in range(1, S)]
        a0 = As[0] or 1e-12; aerr = [abs(As[k] / a0 - p['amp'][k] / p['amp'][0]) for k in range(1, S)]
        line = (f"tick {s.j:4d} K={p['K']:2d} N={p['N']:+d} duty={s.d:.3f} resid={rr:.1e} "
                f"max d_k err={max(derr):6.2f} deg  max A_k/A_0 err={max(aerr):.3f}")
        if s.v:
            line += "\n   d_k meas(deg): " + " ".join(f"{360*x:6.1f}" for x in dm[1:]) + \
                    "\n   d_k want(deg): " + " ".join(f"{360*x:6.1f}" for x in de[1:])
        print(line, flush=True)
        return dict(j=s.j, K=p['K'], d=dm, A=[a / a0 for a in As], u0=us[0], derr=derr, aerr=aerr)


# ---------------------------------------------------------------- front ends
def mk_engine(a): return Engine(a.fs, a.f0, a.stages, float(a.duty) if a.duty != 'auto' else .2, a.hold, a.kmax, a.r, a.am)
def mk_tracker(a, e): return Tracker(e, a.chan, a.hpf, None if a.duty == 'auto' else float(a.duty), a.guard, a.t0, 0, a.v, not a.norefine)

def cmd_loop(a):
    e = mk_engine(a); tr = mk_tracker(a, e); ch = Channel(a.fs, a.hpf, a.noise); blk = a.fs // 10; n0 = 0
    t_start = time.time(); total = int(a.secs * a.fs)
    while n0 < total:
        x = ch(e.render(n0, blk)); tr.feed(x[:, a.chan]); n0 += blk
        if a.speed > 0:
            lag = n0 / a.fs / a.speed - (time.time() - t_start)
            if lag > 0: time.sleep(lag)

def sd():
    try: import sounddevice as sd; return sd
    except Exception as ex: raise SystemExit(f"sounddevice unavailable ({ex}); use synth/track or loop, or pip install sounddevice")

def cmd_play(a):
    e = mk_engine(a); s = sd(); pos = [0]; g = a.gain / (1 + abs(a.am)) / sum(e.mag ** k for k in range(e.S))
    def cb(out, frames, ti, st):
        out[:] = e.render(pos[0], frames) * g; pos[0] += frames
    print(f"playing {a.stages} stages, f0={a.f0} Hz, tick={e.W:.2f} s (ctrl-c to stop). Remember: a sound card is AC-coupled; "
          f"S0 at {a.f0} Hz needs a DC-coupled DAC/amp.")
    with s.OutputStream(samplerate=a.fs, channels=2, device=a.dev, callback=cb, dtype='float32'): 
        while True: time.sleep(1)

def cmd_live(a):
    import queue
    e = mk_engine(a); tr = mk_tracker(a, e); q = queue.Queue(); s = sd()
    def cb(inp, frames, ti, st): q.put(inp[:, min(a.chan, inp.shape[1] - 1)].astype(float).copy())
    with s.InputStream(samplerate=a.fs, channels=2, device=a.dev, callback=cb):
        while True: tr.feed(q.get())

def cmd_synth(a):
    e = mk_engine(a); n = int(a.secs * a.fs); x = e.render(0, n)
    x = x - x.mean(0); rng = np.random.default_rng(1)
    if a.hpf > 0:
        X = np.fft.rfft(x, axis=0); f = np.fft.rfftfreq(n, 1 / a.fs); X *= hpf(f, a.hpf)[:, None]; x = np.fft.irfft(X, n, axis=0)
    x = x + a.noise * rng.standard_normal(x.shape)
    pcm = (0.5 * x / np.abs(x).max() * 32767).astype('<i2')
    with wave.open(a.out, 'wb') as w: w.setnchannels(2); w.setsampwidth(2); w.setframerate(a.fs); w.writeframes(pcm.tobytes())
    print(f"wrote {a.out}: stereo, ch0=S+ ch1=S-, {n/a.fs:.0f} s, tick {e.W:.3f} s ({a.hold} periods), kmax {a.kmax}")

def cmd_track(a):
    w = wave.open(a.file); a.fs = w.getframerate(); ch = w.getnchannels()
    x = np.frombuffer(w.readframes(w.getnframes()), '<i2').astype(float).reshape(-1, ch)
    e = mk_engine(a); tr = mk_tracker(a, e); xs = x[:, min(a.chan, ch - 1)]
    for i in range(0, len(xs), a.fs): tr.feed(xs[i:i + a.fs])

if __name__ == "__main__":
    p = argparse.ArgumentParser(); sp = p.add_subparsers(dest="cmd", required=True)
    def common(q, tx=True):
        q.add_argument("--fs", type=int, default=8000); q.add_argument("--f0", type=float, default=.979)
        q.add_argument("--stages", type=int, default=7); q.add_argument("--duty", default="0.2", help="float, or 'auto' (tracker fits it)")
        q.add_argument("--hold", type=int, default=4, help="ring tick = this many periods of T0")
        q.add_argument("--kmax", type=int, default=21, help="ring wraps to (0,1) after this many ticks")
        q.add_argument("--r", type=float, default=.743, help="Psi radius; per-octave amplitude = sqrt(phi) r^phi (.743 -> .786)")
        q.add_argument("--am", type=float, default=0., help="Cassini-parity AM depth, 1+am*N")
        q.add_argument("--hpf", type=float, default=0.); q.add_argument("--chan", type=int, default=0, help="0=S+, 1=S-")
        q.add_argument("--guard", type=float, default=.5, help="T0 skipped at each tick edge by the tracker")
        q.add_argument("--t0", type=float, default=0., help="rx time offset (s)"); q.add_argument("-v", dest="v", action="store_true"); q.add_argument("--norefine", action="store_true", help="peel only (no joint LSQ)")
        q.add_argument("--dev", default=None); q.add_argument("--gain", type=float, default=.8)
    for name, f in (("loop", cmd_loop), ("play", cmd_play), ("live", cmd_live), ("synth", cmd_synth), ("track", cmd_track)):
        q = sp.add_parser(name); q.set_defaults(fn=f)
        if name == "synth": q.add_argument("out")
        if name == "track": q.add_argument("file")
        common(q)
        if name in ("loop", "synth"): q.add_argument("--secs", type=float, default=60.); q.add_argument("--noise", type=float, default=.02)
        if name == "loop": q.add_argument("--speed", type=float, default=1., help="wall-clock factor; 0 = as fast as possible")
    a = p.parse_args(); a.fn(a)
