"""Core: spectrogram, Doppler model, curve scoring."""
import numpy as np, soundfile as sf, glob
from scipy import signal
from scipy.ndimage import median_filter
C=343.0
def load(path,sr=8000):
    fs=sorted(glob.glob(path)) if isinstance(path,str) else path
    x=np.concatenate([sf.read(f,dtype="float32")[0] for f in fs]); return x,sr
class Spec:
    def __init__(s,x,sr=8000,win=4.0,hop=0.5,fmax=500.0,fmin=20.0):
        n=int(win*sr); h=int(hop*sr)
        fr,t,Z=signal.stft(x,sr,window="hann",nperseg=n,noverlap=n-h,boundary=None,padded=False)
        k=(fr>=fmin)&(fr<=fmax); P=np.abs(Z[k]).astype(np.float32)**2
        s.f=fr[k]; s.t=t; s.df=s.f[1]-s.f[0]; s.hop=hop
        L=10*np.log10(P+1e-12)
        # per-frequency whitening: subtract a slow running median so stationary hum/tones vanish, and per-frame broadband level
        L=L-np.median(L,axis=1,keepdims=True)
        L=L-median_filter(L,size=(31,1),mode="nearest")
        s.Z=L/(1.4826*np.median(np.abs(L))+1e-6)
    def sample(s,t,f):
        i=np.clip(((t-s.t[0])/s.hop).round().astype(int),0,len(s.t)-1)
        j=np.clip(((f-s.f[0])/s.df).round().astype(int),0,len(s.f)-1)
        return s.Z[j,i]
ER=6371000.0
def enu(lat,lon,alt,lat0,lon0):
    return np.c_[np.radians(lon-lon0)*ER*np.cos(np.radians(lat0)),np.radians(lat-lat0)*ER,alt]
def heard(tau,src,obs,c=C):
    """Emission-time model. Returns arrival time, Doppler ratio f/f0, range."""
    r=np.linalg.norm(src-obs,axis=-1); vr=np.gradient(r,tau,axis=-1)
    return tau+r/c, c/(c+vr), r
def straight(t,v,d,tc,c=C):
    """Exact retarded-time Doppler ratio for straight flight; tc = heard CPA time."""
    tp=np.asarray(t,float)-tc+d/c
    tau=(c*c*tp-c*np.sqrt(v*v*tp*tp+(1-(v/c)**2)*d*d))/(c*c-v*v)
    vr=v*v*tau/np.sqrt(d*d+v*v*tau*tau)
    return c/(c+vr)

def ridge(S,t0,t1,fl,fh,max_jump_hz=2.0,jump_cost=1.0):
    """Viterbi ridge through whitened spectrogram: returns t,f,weight."""
    i=(S.t>=t0)&(S.t<=t1); j=(S.f>=fl)&(S.f<=fh)
    Z=np.clip(S.Z[j][:,i],-1,8); T=S.t[i]; F=S.f[j]
    mj=max(1,int(max_jump_hz*S.hop/S.df*2))
    n,m=Z.shape; D=Z[:,0].copy(); B=np.zeros((n,m),int)
    off=np.arange(-mj,mj+1); pen=jump_cost*np.abs(off)/mj
    for k in range(1,m):
        C=np.stack([np.roll(D,o)-p for o,p in zip(off,pen)])
        for q,o in enumerate(off):
            if o>0: C[q,:o]=-1e9
            elif o<0: C[q,o:]=-1e9
        a=C.argmax(0); D=C[a,np.arange(n)]+Z[:,k]; B[:,k]=np.arange(n)-off[a]
    p=np.zeros(m,int); p[-1]=D.argmax()
    for k in range(m-1,0,-1): p[k-1]=B[p[k],k]
    return T,F[p],Z[p,np.arange(m)]
def fit_flyover(t,f,w,c=C,minw=2.0):
    from scipy.optimize import least_squares
    k=w>=minw; t,f=t[k],f[k]
    if len(t)<20: return None
    def res(p): return p[0]*straight(t,p[1],np.exp(p[2]),p[3],c)-f
    best=None
    for v0 in (40,70,100,130):
      for d0 in (500,1500,3000):
        fm=np.median(f); r=least_squares(res,[fm,v0,np.log(d0),t[np.argmin(np.abs(f-fm))]],loss="soft_l1",f_scale=1.0,
             bounds=([10,15,np.log(100),t[0]-30],[600,200,np.log(15000),t[-1]+30]))
        if best is None or r.cost<best.cost: best=r
    p=best.x; e=res(p); J=best.jac
    try:
        cov=np.linalg.inv(J.T@J)*np.median(np.abs(e))**2*2.2; sd=np.sqrt(np.diag(cov))
    except Exception: sd=np.full(4,np.nan)
    return dict(f0=p[0],v=p[1],d=float(np.exp(p[2])),tc=p[3],rms=float(np.sqrt(np.median(e**2))*1.48),n=len(t),sd_v=sd[1],sd_d=float(np.exp(p[2])*sd[2]),sd_tc=sd[3],sd_f0=sd[0])

def to_logf(S,fmin=40.,fmax=420.,ratio=1.003,hop=1.0):
    """Resample whitened spectrogram to log-frequency / coarse time; Doppler templates become translation invariant."""
    nb=int(np.log(fmax/fmin)/np.log(ratio)); lf=fmin*ratio**np.arange(nb)
    jj=np.clip(np.searchsorted(S.f,lf),1,len(S.f)-1)
    st=max(1,int(round(hop/S.hop))); nT=S.Z.shape[1]//st
    Zc=np.clip(S.Z,0,7)
    L=np.zeros((nb,nT),np.float32)
    # max-pool over the frequency width of each log bin and over time step
    wid=np.maximum(1,(lf*(ratio-1)/S.df).astype(int))
    for b,(j,w) in enumerate(zip(jj,wid)):
        r=Zc[max(0,j-w):j+w].max(0)
        L[b]=r[:nT*st].reshape(nT,st).max(1)
    return L,lf,S.t[0]+np.arange(nT)*st*S.hop+st*S.hop/2,hop

def detect(S,c=C,vs=np.arange(42,156,6.),ds=np.geomspace(200,12000,20),top=30,workers=8,sep=25.,hop=1.0,ratio=1.003,log=None):
    """Doppler matched filter over the recording. Returns candidate flyovers sorted by score.
    The score is the min over three parts of the curve (approach tail, drop, departure tail) so a flat tone cannot score."""
    from scipy import fft as F
    L,lf,tt,hop=to_logf(S,hop=hop,ratio=ratio)
    # machine tones occupy their bands for much of the recording: blank them so they cannot steer the filter
    occ=(L>3.5).mean(1); hum=occ>np.median(occ)+3*1.48*np.median(np.abs(occ-np.median(occ)))
    L=L-L.mean(); L[hum]=0
    if log: log("hum bins %d/%d"%(hum.sum(),len(hum)))
    nb,nT=L.shape; lr=np.log(ratio)
    FL=F.rfft2(L,s=(2*nb,nT+400),workers=workers)
    best=np.full((nb,nT),-1e9,np.float32); bv=np.zeros((nb,nT),np.float32); bd=np.zeros((nb,nT),np.float32)
    for v in vs:
      for d in ds:
        tv=d/v; T=max(25.,min(90.,4*tv)); tau=np.arange(-T,T+hop,hop); y=np.log(straight(tau,v,d,0.,c))/lr
        if y.max()-y.min()<np.log(1.15)/lr: continue   # visible drop under 15%: indistinguishable from drift
        y=np.round(y).astype(int)
        mid=np.abs(tau)<=max(4,1.2*tv); parts=[mid,tau<-1.2*tv,tau>1.2*tv]
        sc=[]
        for m in parts:
            if m.sum()<4: continue
            k=np.zeros((2*nb,nT+400),np.float32)
            # correlation: template placed so that (tc index, f0 index) is output coordinate
            k[y[m]%(2*nb),np.round(tau[m]/hop).astype(int)%(nT+400)]=1/np.sqrt(m.sum())
            cc=F.irfft2(FL*np.conj(F.rfft2(k,workers=workers)),s=(2*nb,nT+400),workers=workers)[:nb,:nT]
            sc.append(cc)
        # need the drop itself plus at least one tail (the other tail is often hidden)
        s=np.minimum(sc[0],np.max(sc[1:],axis=0))*np.sqrt(2) if len(sc)>1 else sc[0]
        u=s>best; best[u]=s[u]; bv[u]=v; bd[u]=d
    # non-maximum suppression in time
    out=[]; B=best.copy()
    for _ in range(top):
        b,i=np.unravel_index(np.argmax(B),B.shape)
        if B[b,i]<=0: break
        out.append(dict(score=float(B[b,i]),f0=float(lf[b]),tc=float(tt[i]),v=float(bv[b,i]),d=float(bd[b,i])))
        w=int(sep/hop); fr=np.abs(np.log(lf/lf[b]))<0.5
        B[np.ix_(fr,np.arange(max(0,i-w),min(nT,i+w+1)))]=-1e9
    return out

def line_score(S,tau,src,obs,f0,dt=0.,c=C,nh=(1,)):
    """Mean clipped whitened power along the predicted line."""
    ta,ra,_=heard(tau,src,obs,c); out=0.
    for h in nh: out=out+np.clip(S.sample(ta+dt,h*f0*ra),-1,7)
    return out.mean()/len(nh)

def refine(S,e,c=C,span=None):
    """Polish (f0,v,d,tc) by maximising line power then return with crude bounds from the score surface."""
    from scipy.optimize import minimize
    def obj(p):
        f0,v,ld,tc=p; d=np.exp(ld); T=max(25.,min(90.,4*d/v)); t=np.arange(tc-T,tc+T,S.hop)
        f=f0*straight(t,v,d,tc,c); return -np.clip(S.sample(t,f),-1,7).mean()
    x0=[e["f0"],e["v"],np.log(e["d"]),e["tc"]]; best=None
    for mult in (1,):
        r=minimize(obj,x0,method="Nelder-Mead",options=dict(maxiter=1500,xatol=1e-2,fatol=1e-3,initial_simplex=np.array([x0]+[np.array(x0)+np.eye(4)[i]*[1.5,6,.15,2][i] for i in range(4)])))
        best=r
    f0,v,ld,tc=best.x
    # ranges where the score stays within 90% of peak
    def rng(i,grid):
        base=-best.fun; g=[g0 for g0 in grid if -obj(np.where(np.arange(4)==i,g0,best.x))>=0.9*base]
        return (min(g),max(g)) if g else (best.x[i],best.x[i])
    vr=rng(1,np.arange(max(25,v-30),v+30,1.)); dr=rng(2,np.log(np.geomspace(max(100,np.exp(ld)/2.5),np.exp(ld)*2.5,40))); tr=rng(3,np.arange(tc-12,tc+12,.25))
    return dict(f0=f0,v=v,d=float(np.exp(ld)),tc=tc,line=-best.fun,v_rng=vr,d_rng=(float(np.exp(dr[0])),float(np.exp(dr[1]))),tc_rng=tr,score=e.get("score"))
def chirp_contrast_features(S, e, c=C, flat_grid_steps=15):
    """Score whether a candidate Doppler peak reflects a true downward glide rather than a stationary bell/harmonic tone."""
    f0, v, d, tc = float(e["f0"]), float(e["v"]), float(e["d"]), float(e["tc"])
    tv = max(3.0, d / v)
    span = max(14.0, min(42.0, 2.0 * tv))
    t0 = max(float(S.t[0]), tc - span)
    t1 = min(float(S.t[-1]), tc + span)
    fl = max(float(S.f[0]), f0 * 0.72)
    fh = min(float(S.f[-1]), f0 * 1.32)

    # 1. Line integral along the candidate Doppler curve vs best stationary constant frequency
    t_line = np.arange(t0, t1 + 1e-6, S.hop)
    f_curve = f0 * straight(t_line, v, d, tc, c)
    doppler_line = float(np.clip(S.sample(t_line, f_curve), -1.0, 7.0).mean())

    flat_vals = []
    for fc in np.linspace(fl, fh, flat_grid_steps):
        flat_vals.append(float(np.clip(S.sample(t_line, np.full_like(t_line, fc)), -1.0, 7.0).mean()))
    best_flat_line = max(flat_vals) if flat_vals else 0.0

    # Check both pre-tc and post-tc energy strictly along the predicted Doppler curve
    pre_m = t_line < tc - 0.15 * span
    post_m = t_line > tc + 0.15 * span
    pre_line = float(np.clip(S.sample(t_line[pre_m], f_curve[pre_m]), -1.0, 7.0).mean()) if pre_m.any() else -1.0
    post_line = float(np.clip(S.sample(t_line[post_m], f_curve[post_m]), -1.0, 7.0).mean()) if post_m.any() else -1.0

    # 2. Extract Viterbi ridge around (tc, f0) and measure monotone frequency glide + model fit gain
    tr, fr, wr = ridge(S, t0, t1, fl, fh, max_jump_hz=3.5, jump_cost=0.8)
    valid = wr >= 0.6
    if valid.sum() >= 8:
        tv_r, fv_r, wv_r = tr[valid], fr[valid], wr[valid]
    else:
        tv_r, fv_r, wv_r = tr, fr, np.maximum(wr, 0.1)

    n_edge = max(2, len(fv_r) // 3)
    f_early = float(np.median(fv_r[:n_edge]))
    f_late = float(np.median(fv_r[-n_edge:]))
    glide_drop_pct = 100.0 * (f_early - f_late) / max(f0, 1e-6)

    # Smoothed frame-to-frame negative frequency slope fraction
    if len(fv_r) >= 5:
        kern = np.ones(3) / 3.0
        fs = np.convolve(fv_r, kern, mode="valid")
        df = np.diff(fs)
        mono_neg_frac = float((df <= 0.15).mean())
    else:
        mono_neg_frac = 0.0

    # Weighted RMSE ratio: Doppler curve fit vs optimal constant tone on the extracted ridge
    f_pred = f0 * straight(tv_r, v, d, tc, c)
    w_norm = wv_r / (wv_r.sum() + 1e-9)
    rms_doppler = float(np.sqrt(np.sum(w_norm * (fv_r - f_pred) ** 2)))
    rms_const = float(np.sqrt(np.sum(w_norm * (fv_r - np.sum(w_norm * fv_r)) ** 2)))
    fit_gain = 1.0 - rms_doppler / (rms_const + 1e-6)

    return dict(
        doppler_line=round(doppler_line, 3),
        best_flat_line=round(best_flat_line, 3),
        doppler_margin=round(doppler_line - best_flat_line, 3),
        pre_line=round(pre_line, 3),
        post_line=round(post_line, 3),
        glide_drop_pct=round(glide_drop_pct, 2),
        mono_neg_frac=round(mono_neg_frac, 3),
        rms_doppler_hz=round(rms_doppler, 2),
        rms_const_hz=round(rms_const, 2),
        fit_gain=round(fit_gain, 3),
    )


def detect_v2(
    S,
    c=C,
    vs=np.arange(42, 156, 6.0),
    ds=np.geomspace(200, 12000, 20),
    top=30,
    workers=8,
    sep=25.0,
    hop=1.0,
    ratio=1.003,
    min_score=3.2,
    min_glide_pct=4.5,
    min_fit_gain=0.25,
    min_doppler_margin=0.25,
    min_mono_neg=0.55,
    log=None,
):
    """Upgraded Doppler detector with adaptive short-clip hum masking and chirp-slope rejection.
    1) On short urban clips (<= 10 min), only blanks truly persistent tones (occ > 0.65) so a
       30s aircraft flyover does not blank its own approach/departure tails.
    2) Rejects stationary bell partials, traffic rumbles, and strikes via chirp_contrast_features."""
    from scipy import fft as F
    L, lf, tt, hop = to_logf(S, hop=hop, ratio=ratio)
    occ = (L > 3.5).mean(1)
    if L.shape[1] <= 600:
        hum = occ > 0.65
    else:
        hum = occ > np.median(occ) + 3 * 1.48 * np.median(np.abs(occ - np.median(occ)))
    L = L - L.mean()
    L[hum] = 0
    if log:
        log("v2 hum bins %d/%d" % (hum.sum(), len(hum)))
    nb, nT = L.shape
    lr = np.log(ratio)
    FL = F.rfft2(L, s=(2 * nb, nT + 400), workers=workers)
    best = np.full((nb, nT), -1e9, np.float32)
    bv = np.zeros((nb, nT), np.float32)
    bd = np.zeros((nb, nT), np.float32)
    for v in vs:
        for d in ds:
            tv = d / v
            T = max(25.0, min(90.0, 4 * tv))
            tau = np.arange(-T, T + hop, hop)
            y = np.log(straight(tau, v, d, 0.0, c)) / lr
            if y.max() - y.min() < np.log(1.15) / lr:
                continue
            y = np.round(y).astype(int)
            mid = np.abs(tau) <= max(4, 1.2 * tv)
            parts = [mid, tau < -1.2 * tv, tau > 1.2 * tv]
            sc = []
            for m in parts:
                if m.sum() < 4:
                    continue
                k = np.zeros((2 * nb, nT + 400), np.float32)
                k[y[m] % (2 * nb), np.round(tau[m] / hop).astype(int) % (nT + 400)] = 1 / np.sqrt(m.sum())
                cc = F.irfft2(FL * np.conj(F.rfft2(k, workers=workers)), s=(2 * nb, nT + 400), workers=workers)[:nb, :nT]
                sc.append(cc)
            if len(sc) == 3:
                # Require centered two-sided balance (mean of tails + mild min-tail floor) so flat 1-sided tails cannot NMS-suppress true CPAs
                tail_score = 0.65 * (0.5 * sc[1] + 0.5 * sc[2]) + 0.35 * np.minimum(sc[1], sc[2])
                s = np.minimum(sc[0], tail_score) * np.sqrt(2)
            elif len(sc) > 1:
                s = np.minimum(sc[0], np.max(sc[1:], axis=0)) * np.sqrt(2)
            else:
                s = sc[0]
            u = s > best
            best[u] = s[u]
            bv[u] = v
            bd[u] = d

    accepted, rejected = [], []
    B = best.copy()
    max_iters = max(48, top * 8)
    for _ in range(max_iters):
        if len(accepted) >= top:
            break
        b, i = np.unravel_index(np.argmax(B), B.shape)
        if B[b, i] < min_score:
            break
        cand = dict(score=float(B[b, i]), f0=float(lf[b]), tc=float(tt[i]), v=float(bv[b, i]), d=float(bd[b, i]))
        feats = chirp_contrast_features(S, cand, c=c)
        enriched = {**cand, **feats}
        ok = (
            cand["score"] >= min_score
            and feats["glide_drop_pct"] >= min_glide_pct
            and feats["fit_gain"] >= min_fit_gain
            and feats["doppler_margin"] >= min_doppler_margin
            and feats["mono_neg_frac"] >= min_mono_neg
            and max(feats["pre_line"], feats["post_line"]) > 0.5
        )
        enriched["accepted_v2"] = bool(ok)
        if ok:
            accepted.append(enriched)
            w = int(sep / hop)
            fr = np.abs(np.log(lf / lf[b])) < 0.5
            B[np.ix_(fr, np.arange(max(0, i - w), min(nT, i + w + 1)))] = -1e9
        else:
            if len(rejected) < top:
                rejected.append(enriched)
            # Only suppress tight local lobe around a rejected bell/hum artifact so neighboring aircraft tracks survive
            w_rej = max(2, int(6.0 / hop))
            fr_rej = np.abs(np.log(lf / lf[b])) < 0.08
            B[np.ix_(fr_rej, np.arange(max(0, i - w_rej), min(nT, i + w_rej + 1)))] = -1e9
    return accepted, rejected


def load_spec(p):
    z=np.load(p); S=Spec.__new__(Spec); S.Z=z["Z"].astype(float); S.f=z["f"]; S.t=z["t"]; S.df=S.f[1]-S.f[0]; S.hop=S.t[1]-S.t[0]; return S
