import sys
import numpy as np
from scipy.io import wavfile
from scipy.signal import correlate, stft

# Spectral-flux FFT cross-correlation (mic-robust, fingerprint-style).
# Usage: sync_spec.py A.wav B.wav -> lag_s r ratio   (B starts at A+lag_s; ratio=peak/p99 = confidence)

def flux(path, fps=100):
    sr, x = wavfile.read(path)
    if x.ndim > 1:
        x = x.mean(axis=1)
    x = x.astype(np.float64)
    nseg = 1024
    hop = max(1, sr // fps)
    _, _, Z = stft(x, nperseg=nseg, noverlap=nseg - hop, boundary=None)
    mag = np.abs(Z)
    d = np.diff(mag, axis=1)
    fl = np.maximum(d, 0.0).sum(axis=0)
    return fl, sr / hop

def z(v):
    v = v - v.mean()
    s = v.std()
    return v / (s if s else 1.0)

fa, fps = flux(sys.argv[1])
fb, _ = flux(sys.argv[2])
swap = len(fb) > len(fa)
A, B = (fb, fa) if swap else (fa, fb)
A, B = z(A), z(B)
c = correlate(A, B, mode='valid', method='fft') / len(B)
i = int(np.argmax(c))
peak = float(c[i])
p99 = float(np.percentile(np.abs(c), 99)) or 1e-9
ratio = peak / p99
lag_s = i / fps
if swap:
    lag_s = -lag_s
print(f"lag_s={lag_s:.3f} r={peak:.3f} ratio={ratio:.2f}")
