#!/usr/bin/env python3
"""
Step 3: Acoustic OSINT geolocation & real doppler-geo (dg.py) overflight analysis
across public Big Ben recordings.
"""
import json, math, os, subprocess, sys, tempfile
import numpy as np
import soundfile as sf
from scipy.signal import butter, sosfilt, find_peaks, resample_poly
from scipy.signal.windows import hann

sys.path.insert(0, os.environ.get("DOPPLER_GEO_CODE", "doppler-geo/code"))
import dg  # exact doppler-geo core

CORPUS_DIR = os.environ.get(
    "BIG_BEN_CORPUS",
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "corpus"),
)
OUT_DIR = os.environ.get(
    "BIG_BEN_OUT",
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "out"),
)
os.makedirs(OUT_DIR, exist_ok=True)

TOWER_LAT, TOWER_LON, TOWER_Z = 51.500729, -0.124625, 65.0

def hav_m(lat1, lon1, lat2, lon2):
    R = 6371000.0
    p1, p2 = math.radians(lat1), math.radians(lat2)
    a = math.sin(math.radians(lat2 - lat1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2
    return 2 * R * math.asin(math.sqrt(a))

def bearing_deg(lat1, lon1, lat2, lon2):
    dl = math.radians(lon2 - lon1)
    y = math.sin(dl) * math.cos(math.radians(lat2))
    x = math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) - math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(dl)
    return (math.degrees(math.atan2(y, x)) + 360.0) % 360.0

def load_stereo(fname):
    fp = os.path.join(CORPUS_DIR, fname)
    if fname.endswith((".wav", ".flac", ".ogg")):
        try:
            x, sr = sf.read(fp, always_2d=True)
            if x.shape[1] == 1:
                x = np.column_stack([x[:, 0], x[:, 0]])
            return x[:, :2].astype(np.float64), int(sr)
        except Exception:
            pass
    with tempfile.NamedTemporaryFile(suffix=".wav") as tf:
        subprocess.run(["ffmpeg", "-y", "-i", fp, "-ac", "2", tf.name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
        x, sr = sf.read(tf.name, always_2d=True)
        return x[:, :2].astype(np.float64), int(sr)

def gcc_phat_itd(sig_l, sig_r, sr, max_tau_ms=1.2):
    n = len(sig_l) + len(sig_r)
    nfft = 1 << (n - 1).bit_length()
    L = np.fft.rfft(sig_l * hann(len(sig_l), sym=False), n=nfft)
    R = np.fft.rfft(sig_r * hann(len(sig_r), sym=False), n=nfft)
    G = L * np.conj(R)
    cc = np.fft.irfft(G / (np.abs(G) + 1e-12), n=nfft)
    max_shift = int((max_tau_ms / 1000.0) * sr)
    cc = np.concatenate((cc[-max_shift:], cc[: max_shift + 1]))
    lags_ms = np.arange(-max_shift, max_shift + 1) * (1000.0 / sr)
    k = int(np.argmax(cc))
    if 0 < k < len(cc) - 1:
        y0, y1, y2 = cc[k - 1], cc[k], cc[k + 1]
        denom = y0 - 2 * y1 + y2
        delta = 0.5 * (y0 - y2) / denom if abs(denom) > 1e-12 else 0.0
        tau_ms = float(lags_ms[k] + delta * (1000.0 / sr))
    else:
        tau_ms = float(lags_ms[k])
    peak_coh = float(cc[k] / (np.std(cc) + 1e-12))
    return tau_ms, peak_coh

def wiener_rir_deconv(y, s_ref, sr, reg=1e-2):
    n = max(len(y), len(s_ref))
    nfft = 1 << (n - 1).bit_length()
    Y = np.fft.rfft(y * hann(len(y), sym=False), n=nfft)
    S = np.fft.rfft(s_ref * hann(len(s_ref), sym=False), n=nfft)
    fr = np.fft.rfftfreq(nfft, 1.0 / sr)
    mask = (fr >= 150.0) & (fr <= 2200.0)
    S_pow = np.abs(S) ** 2
    lam = reg * np.max(S_pow[mask])
    H = np.zeros_like(Y)
    H[mask] = (Y[mask] * np.conj(S[mask])) / (S_pow[mask] + lam)
    h = np.fft.irfft(H, n=nfft)
    h_search = h[: int(1.5 * sr)]
    pk = int(np.argmax(np.abs(h_search)))
    i0 = max(0, pk - int(0.004 * sr))
    i1 = min(len(h_search), pk + int(0.008 * sr))
    i2 = min(len(h_search), pk + int(0.080 * sr))
    i3 = min(len(h_search), pk + int(0.600 * sr))
    e_dir = float(np.sum(h_search[i0:i1] ** 2)) + 1e-18
    e_early = float(np.sum(h_search[i1:i2] ** 2)) + 1e-18
    e_late = float(np.sum(h_search[i2:i3] ** 2)) + 1e-18
    drr_db = 10.0 * math.log10(e_dir / (e_early + e_late))
    refl_seg = np.abs(h_search[i1 : min(len(h_search), pk + int(0.120 * sr))])
    refl_pks, _ = find_peaks(refl_seg, height=np.max(refl_seg) * 0.45, distance=int(0.004 * sr))
    first_refl_ms = float((refl_pks[0] + int(0.008 * sr)) * 1000.0 / sr) if len(refl_pks) else None
    return round(drr_db, 2), round(first_refl_ms, 1) if first_refl_ms else None

def band_ratio_db(x_mono, sr, onsets, bands_num, bands_den, win_s=1.0):
    e_num, e_den = 0.0, 0.0
    for t0 in onsets:
        i0 = int(t0 * sr)
        i1 = min(len(x_mono), i0 + int(win_s * sr))
        if i1 - i0 < int(0.35 * sr): continue
        seg = x_mono[i0:i1]
        sp = np.abs(np.fft.rfft(seg * hann(len(seg), sym=False), n=65536)) ** 2
        fr = np.fft.rfftfreq(65536, 1.0 / sr)
        for fc in bands_num:
            e_num += float(np.sum(sp[(fr >= fc - 9) & (fr <= fc + 9)]))
        for fc in bands_den:
            e_den += float(np.sum(sp[(fr >= fc - 9) & (fr <= fc + 9)]))
    return round(10.0 * math.log10((e_num + 1e-18) / (e_den + 1e-18)), 2)

def run_real_doppler_geo_detector(fname):
    """Run exact doppler-geo (dg.Spec + dg.detect) on audio downsampled to 8 kHz."""
    fp = os.path.join(CORPUS_DIR, fname)
    with tempfile.NamedTemporaryFile(suffix=".wav") as tf:
        subprocess.run(["ffmpeg", "-y", "-i", fp, "-ac", "1", "-ar", "8000", tf.name],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
        x8, sr8 = sf.read(tf.name, dtype="float32")
    dur = len(x8) / sr8
    if dur < 26.0:
        return {"duration_s": round(dur, 2), "top_score": None, "note": "shorter than 25s minimum Doppler window"}
    S = dg.Spec(x8, sr=8000, win=4.0, hop=0.5, fmax=500.0, fmin=20.0)
    cands = dg.detect(S, top=3, workers=2)
    if not cands:
        return {"duration_s": round(dur, 2), "top_score": 0.0, "n_candidates": 0}
    top = cands[0]
    return {
        "duration_s": round(dur, 2),
        "n_candidates": len(cands),
        "top_score": round(top["score"], 2),
        "top_f0_hz": round(top["f0"], 1),
        "top_v_ms": round(top["v"], 1),
        "top_d_m": round(top["d"], 1),
        "top_tc_s": round(top["tc"], 1),
    }

def main():
    x_42, sr_42 = load_stereo("07002142.wav")
    s_bb_ref = x_42[int(24.80 * sr_42) : int(28.80 * sr_42), :].mean(axis=1)
    x_39, _ = load_stereo("07002139.wav")
    s_q_ref = x_39[int(0.70 * sr_42) : int(2.50 * sr_42), :].mean(axis=1)

    sites = [
        {
            "id": "bbc_1969_belfry_q1",
            "file": "07002139.wav",
            "truth_name": "Elizabeth Tower Belfry (Q1)",
            "truth_class": "belfry",
            "truth_slant_m": 10.0, "truth_az_deg": None,
            "quarter_onsets": [0.75, 1.66, 2.57, 3.29],
            "hour_onsets": [],
            "codec": "WAV 44.1kHz 16-bit",
        },
        {
            "id": "bbc_1969_belfry_1oclock",
            "file": "07002142.wav",
            "truth_name": "Elizabeth Tower Belfry (Q4+1:00)",
            "truth_class": "belfry",
            "truth_slant_m": 10.0, "truth_az_deg": None,
            "quarter_onsets": [0.78, 1.86, 2.58, 3.29, 4.00, 4.59, 5.25, 6.06],
            "hour_onsets": [24.85],
            "codec": "WAV 44.1kHz 16-bit",
        },
        {
            "id": "aporee_2016_bridge_st",
            "file": "aporee_2016_bridge_st.wav",
            "truth_name": "70 Bridge St (Ground-Truth Binaural)",
            "truth_class": "street_close",
            "truth_slant_m": round(math.sqrt(hav_m(TOWER_LAT, TOWER_LON, 51.500966, -0.124648)**2 + (65.0 - 1.7)**2), 1),
            "truth_az_deg": round(bearing_deg(TOWER_LAT, TOWER_LON, 51.500966, -0.124648), 1),
            "quarter_onsets": [0.88, 1.60, 2.40, 2.93, 3.68, 4.24, 5.02, 5.57],
            "hour_onsets": [],
            "codec": "WAV 48kHz 24-bit",
        },
        {
            "id": "bbc_1969_ground_q1",
            "file": "07002154.wav",
            "truth_name": "Palace Yard / Ground Street (1969)",
            "truth_class": "street_close",
            "truth_slant_m": 95.0, "truth_az_deg": None,
            "quarter_onsets": [2.02, 2.56, 3.02, 3.54],
            "hour_onsets": [],
            "codec": "WAV 44.1kHz 16-bit",
        },
        {
            "id": "fs_388808_westminster_bridge",
            "file": "fs_388808_westminster_bridge.mp3",
            "truth_name": "Westminster Bridge (~200 m E)",
            "truth_class": "street_far",
            "truth_slant_m": round(math.sqrt(hav_m(TOWER_LAT, TOWER_LON, 51.5008, -0.1217)**2 + (65.0 - 1.7)**2), 1),
            "truth_az_deg": round(bearing_deg(TOWER_LAT, TOWER_LON, 51.5008, -0.1217), 1),
            "quarter_onsets": [1.36, 1.84, 2.32, 2.83, 3.42, 4.07, 4.52, 5.30],
            "hour_onsets": [],
            "codec": "MP3 HQ 48kHz",
        },
        {
            "id": "square_lq_parliament_sq",
            "file": "square-lq.mp3",
            "truth_name": "Parliament Square (~160 m WSW)",
            "truth_class": "street_far",
            "truth_slant_m": round(math.sqrt(hav_m(TOWER_LAT, TOWER_LON, 51.5005, -0.1269)**2 + (65.0 - 1.7)**2), 1),
            "truth_az_deg": round(bearing_deg(TOWER_LAT, TOWER_LON, 51.5005, -0.1269), 1),
            "quarter_onsets": [0.93, 1.38, 2.02, 2.68, 3.48, 3.94, 4.54, 5.13],
            "hour_onsets": [46.97],
            "codec": "MP3 LQ 24kHz 68kbps",
        },
        {
            "id": "midnight_hq_2017",
            "file": "midnight-hq.mp3",
            "truth_name": "Street Archive (2017 HQ MP3)",
            "truth_class": "unknown",
            "truth_slant_m": None, "truth_az_deg": None,
            "quarter_onsets": [17.69, 19.77, 20.41, 21.25],
            "hour_onsets": [42.09],
            "codec": "MP3 HQ 44.1kHz 185kbps",
        },
        {
            "id": "midnight_lq_2017",
            "file": "midnight-lq.mp3",
            "truth_name": "Street Archive (2017 LQ MP3)",
            "truth_class": "unknown",
            "truth_slant_m": None, "truth_az_deg": None,
            "quarter_onsets": [17.69, 19.77, 20.41, 21.25],
            "hour_onsets": [42.09],
            "codec": "MP3 LQ 24kHz 67kbps",
        },
        {
            "id": "nye_2024_utc",
            "file": "fs_720696_nye2024.mp3",
            "truth_name": "NYE 2024 (2024-01-01 00:00 UTC)",
            "truth_class": "unknown",
            "truth_slant_m": None, "truth_az_deg": None,
            "quarter_onsets": [1.35, 1.88, 2.47, 3.15, 3.94, 4.64, 5.28, 5.88],
            "hour_onsets": [65.49],
            "codec": "MP3 HQ 44.1kHz",
        },
    ]

    results = []
    for s in sites:
        x_st, sr = load_stereo(s["file"])
        x_m = x_st.mean(axis=1)
        itds, cohs, itds_swap = [], [], []
        sos = butter(4, [300, min(2000, sr * 0.42)], btype="band", fs=sr, output="sos")
        for t0 in s["quarter_onsets"][:6]:
            i0 = max(0, int((t0 - 0.05) * sr))
            i1 = min(len(x_st), i0 + int(0.8 * sr))
            if i1 - i0 < int(0.2 * sr): continue
            sl = sosfilt(sos, x_st[i0:i1, 0])
            sr_ch = sosfilt(sos, x_st[i0:i1, 1])
            tau, coh = gcc_phat_itd(sl, sr_ch, sr, max_tau_ms=1.2)
            tau_sw, _ = gcc_phat_itd(sr_ch, sl, sr, max_tau_ms=1.2)
            itds.append(tau)
            itds_swap.append(tau_sw)
            cohs.append(coh)
        rms_l = math.sqrt(float(np.mean(x_st[:, 0] ** 2)) + 1e-18)
        rms_r = math.sqrt(float(np.mean(x_st[:, 1] ** 2)) + 1e-18)
        ild_db = round(20.0 * math.log10(rms_l / rms_r), 2)

        if s["hour_onsets"]:
            t_h = s["hour_onsets"][0]
            y_seg = x_m[int(t_h * sr) : int(min(len(x_m), (t_h + 4.0) * sr))]
            g = math.gcd(sr, sr_42)
            ref_use = resample_poly(s_bb_ref, sr // g, sr_42 // g) if sr != sr_42 else s_bb_ref
            drr_db, refl_ms = wiener_rir_deconv(y_seg, ref_use, sr)
        else:
            t_q = s["quarter_onsets"][0]
            y_seg = x_m[int(t_q * sr) : int(min(len(x_m), (t_q + 1.8) * sr))]
            g = math.gcd(sr, sr_42)
            ref_use = resample_poly(s_q_ref, sr // g, sr_42 // g) if sr != sr_42 else s_q_ref
            drr_db, refl_ms = wiener_rir_deconv(y_seg, ref_use, sr)

        q_tilt_db = band_ratio_db(x_m, sr, s["quarter_onsets"][:4], [771.0, 870.0], [312.0, 504.0], win_s=0.9)
        bb_tilt_db = band_ratio_db(x_m, sr, s["hour_onsets"], [678.0, 883.0, 1088.0], [200.0, 335.0], win_s=1.2) if s["hour_onsets"] else None

        q_seg = x_m[int(s["quarter_onsets"][0] * sr) : int(min(len(x_m), (s["quarter_onsets"][-1] + 1.5) * sr))]
        sp_q = np.abs(np.fft.rfft(q_seg * hann(len(q_seg), sym=False), n=65536)) ** 2
        fr_q = np.fft.rfftfreq(65536, 1.0 / sr)
        q_band_energies = {bname: float(np.sum(sp_q[(fr_q >= fc - 10) & (fr_q <= fc + 10)]))
                           for bname, fc in [("G#4_870", 870.0), ("F#4_771", 771.0), ("E4_679", 679.0), ("B3_504", 504.0)]}
        q_tot = sum(q_band_energies.values()) + 1e-18
        q_fracs = {k: round(v / q_tot, 3) for k, v in q_band_energies.items()}

        dop = run_real_doppler_geo_detector(s["file"])

        results.append({
            "id": s["id"],
            "truth_name": s["truth_name"],
            "truth_class": s["truth_class"],
            "truth_slant_m": s["truth_slant_m"],
            "truth_az_deg": s["truth_az_deg"],
            "codec": s["codec"],
            "gcc_phat_itd_median_ms": round(float(np.median(itds)), 3) if itds else None,
            "gcc_phat_itd_swapped_ms": round(float(np.median(itds_swap)), 3) if itds_swap else None,
            "gcc_phat_itd_iqr_ms": round(float(np.percentile(itds, 75) - np.percentile(itds, 25)), 3) if len(itds) >= 2 else None,
            "gcc_phat_peak_z": round(float(np.median(cohs)), 2) if cohs else None,
            "binaural_ild_db": ild_db,
            "wiener_drr_db": drr_db,
            "first_reflection_lag_ms": refl_ms,
            "first_reflection_path_diff_m": round(refl_ms * 0.343, 2) if refl_ms else None,
            "quarter_tilt_db": q_tilt_db,
            "big_ben_tilt_db": bb_tilt_db,
            "quarter_bell_louver_fractions": q_fracs,
            "doppler_geo_detector": dop,
        })

    # Also test aporee_2016 vs midnight-hq/lq vs bbc_1969_belfry range prediction
    v_jet, alt_jet, f0_jet, c = 80.0, 1100.0, 150.0, 343.0
    dfdt_cpa_jet = f0_jet * (v_jet ** 2) / (c * alt_jet)
    jet_300m_slant_change_pct = round(100.0 * (math.sqrt(alt_jet ** 2 + 300.0 ** 2) - alt_jet) / alt_jet, 2)
    bell_delay_55_to_355_ms = round((354.5 - 54.7) / c * 1000.0, 1)

    out = {
        "site_osint_observables": results,
        "heathrow_vs_bell_geometry": {
            "heathrow_approach_alt_m": alt_jet,
            "heathrow_approach_speed_ms": v_jet,
            "jet_cpa_chirp_rate_hz_per_s": round(dfdt_cpa_jet, 3),
            "jet_slant_change_over_300m_pct": jet_300m_slant_change_pct,
            "big_ben_lag_span_55m_to_355m_ms": bell_delay_55_to_355_ms,
            "big_ben_utc_hour_anchor": "First hammer blow falls within ~0.1s of :00.000 UTC; acoustic arrival t_arr - t_UTC = slant_m / c + clock_offset",
        },
    }
    with open(os.path.join(OUT_DIR, "osint_geolocation.json"), "w") as f:
        json.dump(out, f, indent=2)
    print("Saved updated osint_geolocation.json")
    for r in results:
        dg_s = r["doppler_geo_detector"].get("top_score")
        print(f"  {r['id']:30s} slant={str(r['truth_slant_m']):>5s}m ITD={str(r['gcc_phat_itd_median_ms']):>6s}ms DRR={str(r['wiener_drr_db']):>5s}dB Q_tilt={r['quarter_tilt_db']:>6.2f}dB BB_tilt={str(r['big_ben_tilt_db']):>6s} dg_score={dg_s}")

if __name__ == "__main__":
    main()
