"""ADS-B (Mode S DF17) dekooder RTL-SDR IQ-salvestisest (1090 MHz, 2.4 MSPS). Ainult numpy.

Kasutus: python adsb.py baseband_1090000000Hz_....wav [--csv out.csv] [--svg map.svg]

Meetod (nagu dump1090): |IQ| -> 2 MSPS -> preambuli otsing (8 µs muster) -> 112 bitti PPM (a > b) ->
CRC-24 (0xFFF409) peab olema 0 -> DF17: ICAO, kutsung (TC 1-4), kõrgus+CPR asukoht (TC 9-18), kiirus (TC 19).
Asukoht: globaalne CPR (paaris+paaritu kaader), varuna lokaalne Tallinna lennujaama (EETN) suhtes.
"""
import argparse, csv, math, os, re, sys, time, wave
import numpy as np

REF_LAT, REF_LON = 59.413, 24.833          # EETN (avalik referents lokaalseks CPR-iks)
CHARS = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ##### ###############0123456789######"


def load_mag(path):
    with wave.open(path, "rb") as w:
        fs, n = w.getframerate(), w.getnframes()
        raw = w.readframes(n)
    d = np.frombuffer(raw, dtype=np.int16)
    i, q = d[0::2].astype(np.float32), d[1::2].astype(np.float32)
    mag = np.sqrt(i * i + q * q)
    return fs, mag


def resample(mag, fs, target=2_000_000):
    n_out = int(len(mag) * target / fs)
    t_out = np.arange(n_out) * (fs / target)
    return np.interp(t_out, np.arange(len(mag)), mag).astype(np.float32)


# ---------------------------------------------------------------- CRC

def crc_check(bits):
    """Tagastab True, kui sõnumi (andmed + paarsus) CRC jääk on 0."""
    msg = 0
    for b in bits:
        msg = (msg << 1) | int(b)
    n = len(bits)
    gen = 0xFFF409
    for i in range(n - 24):
        if msg >> (n - 1 - i) & 1:
            msg ^= gen << (n - 24 - 1 - i)
    return (msg & 0xFFFFFF) == 0


# ---------------------------------------------------------------- preambul + bitid

PRE_CHIPS = np.array([1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], dtype=np.float32)   # 8 µs, 0.5 µs chipid
UP = 12_000_000                                                                              # töö-sagedus kandidaatidel


def find_frames(m, fs, thr_mult=3.0, noise=None):
    """Faasist sõltumatu detektor: impulsside algused (tõusvad servad üle läve) -> kandidaat-aken 12 MSPS-ile
    (lineaarne interpolatsioon) -> preambuli korrelatsioon ±5 µs -> 112 bitti poolbitt-integreerimisega.
    Tagastab list (idx_fs, bits, kvaliteet)."""
    n = len(m)
    if noise is None:
        noise = np.median(m)
    thr = noise * thr_mult
    above = m > thr
    rise = np.where(above[1:] & ~above[:-1])[0] + 1
    if len(rise) == 0:
        return []
    # dedup: üks kandidaat 60 µs (kaadri pikkus 120 µs) kohta
    keep = np.concatenate([[True], np.diff(rise) > int(fs * 60e-6)])
    rise = rise[keep]
    pre = int(fs * 3e-6); win_s = 8e-6 + 112e-6 + 6e-6                          # 3 µs enne, kaader, varu
    win = int(fs * win_s) + pre
    rise = rise[(rise > pre) & (rise + win < n)]
    if len(rise) == 0:
        return []
    K = len(rise)
    # akende tõstmine 12 MSPS-ile: fikseeritud murdosaline võrk
    ratio = fs / UP
    t = np.arange(int(win / ratio)) * ratio
    i0 = t.astype(int); fr = (t - i0).astype(np.float32)
    base = rise[:, None] - pre
    w = m[base + i0] * (1 - fr) + m[base + i0 + 1] * fr                       # (K, L) 12 MSPS
    tpl = np.repeat(PRE_CHIPS, 6); tpl = tpl - tpl.mean()
    Lp = len(tpl)
    shifts = np.arange(0, int(UP * 8e-6))                                        # 0..8 µs
    best_s = np.zeros(K, dtype=int); best_v = np.full(K, -np.inf, dtype=np.float32)
    for s in shifts:
        v = w[:, s:s + Lp] @ tpl
        better = v > best_v
        best_v[better] = v[better]; best_s[better] = s
    # preambuli kvaliteet: tipuchipid vs vaikused
    pidx = best_s[:, None] + np.arange(Lp)
    pw = w[np.arange(K)[:, None], pidx].reshape(K, 16, 6).mean(axis=2)
    highs = pw[:, [0, 2, 7, 9]].mean(axis=1); lows = pw[:, [1, 3, 4, 5, 6, 8, 10, 11, 12, 13, 14, 15]].mean(axis=1)
    ok = (highs > 2.0 * lows) & (highs > thr)
    if not ok.any():
        return []
    w, best_s, rise, highs, lows = w[ok], best_s[ok], rise[ok], highs[ok], lows[ok]
    K = len(rise)
    bidx = best_s[:, None] + Lp + np.arange(112 * 12)
    bw = w[np.arange(K)[:, None], bidx].reshape(K, 112, 12)
    a = bw[:, :, :6].mean(axis=2); b = bw[:, :, 6:].mean(axis=2)
    bits = (a > b).astype(np.uint8)
    conf = (np.abs(a - b) / (a + b + 1e-6)).mean(axis=1)
    return [(int(rise[k]), bits[k], float(conf[k])) for k in range(K)]


# ---------------------------------------------------------------- väljad

def bits_to_int(bits, a, b):
    v = 0
    for x in bits[a:b]:
        v = (v << 1) | int(x)
    return v


def decode_callsign(me):
    cs = ""
    for k in range(8):
        cs += CHARS[bits_to_int(me, 8 + 6 * k, 14 + 6 * k)]
    return cs.replace("#", "").strip()


def decode_altitude(me):
    q = me[15]
    if q:
        n = (bits_to_int(me, 8, 15) << 4) | bits_to_int(me, 16, 20)
        return n * 25 - 1000
    return None                                                # Gray-kood (harv), jätame


def cpr_nl(lat):
    if abs(lat) >= 87:
        return 1
    if lat == 0:
        return 59
    return int(math.floor(2 * math.pi / math.acos(1 - (1 - math.cos(math.pi / 30)) / (math.cos(math.pi / 180 * lat) ** 2))))


def cpr_global(ev, od, t_ev, t_od):
    """Globaalne CPR: paaris (ev) ja paaritu (od) kaadrid (lat_cpr, lon_cpr 0..1)."""
    dlat_e, dlat_o = 360 / 60, 360 / 59
    j = math.floor(59 * ev[0] - 60 * od[0] + 0.5)
    lat_e = dlat_e * ((j % 60) + ev[0]); lat_o = dlat_o * ((j % 59) + od[0])
    if lat_e >= 270: lat_e -= 360
    if lat_o >= 270: lat_o -= 360
    if cpr_nl(lat_e) != cpr_nl(lat_o):
        return None
    if t_ev >= t_od:
        lat, nl = lat_e, cpr_nl(lat_e); ni = max(nl, 1); dlon = 360 / ni
        m = math.floor(ev[1] * (nl - 1) - od[1] * nl + 0.5)
        lon = dlon * ((m % ni) + ev[1])
    else:
        lat, nl = lat_o, cpr_nl(lat_o); ni = max(nl - 1, 1); dlon = 360 / ni
        m = math.floor(ev[1] * (nl - 1) - od[1] * nl + 0.5)
        lon = dlon * ((m % ni) + od[1])
    if lon >= 180: lon -= 360
    return lat, lon


def cpr_local(cpr, odd, ref_lat=REF_LAT, ref_lon=REF_LON):
    dlat = 360 / (59 if odd else 60)
    j = math.floor(ref_lat / dlat) + math.floor(0.5 + (ref_lat % dlat) / dlat - cpr[0])
    lat = dlat * (j + cpr[0])
    nl = cpr_nl(lat) - (1 if odd else 0)
    dlon = 360 / max(nl, 1)
    m = math.floor(ref_lon / dlon) + math.floor(0.5 + (ref_lon % dlon) / dlon - cpr[1])
    lon = dlon * (m + cpr[1])
    return lat, lon


def decode_velocity(me):
    st = bits_to_int(me, 5, 8)
    if st in (1, 2):
        ew_sign, ew = me[13], bits_to_int(me, 14, 24)
        ns_sign, ns = me[24], bits_to_int(me, 25, 35)
        if ew == 0 or ns == 0:
            return None
        vx = (ew - 1) * (-1 if ew_sign else 1); vy = (ns - 1) * (-1 if ns_sign else 1)
        spd = math.hypot(vx, vy); hdg = (math.degrees(math.atan2(vx, vy)) + 360) % 360
        vr_sign, vr = me[36], bits_to_int(me, 37, 46)
        vrate = (vr - 1) * 64 * (-1 if vr_sign else 1) if vr else None
        return spd, hdg, vrate, "GS"
    if st in (3, 4):                                           # õhukiirus + magnetkurss (GNSS puudub!)
        hdg = bits_to_int(me, 14, 24) * 360 / 1024 if me[13] else None
        spd = bits_to_int(me, 25, 35)
        spd = (spd - 1) if spd else None
        vr_sign, vr = me[36], bits_to_int(me, 37, 46)
        vrate = (vr - 1) * 64 * (-1 if vr_sign else 1) if vr else None
        return spd, hdg, vrate, "AS"
    return None


# ---------------------------------------------------------------- pealogika

def decode_file(path, chunk_s=1.0):
    fs, mag = load_mag(path)
    dur = len(mag) / fs
    noise = float(np.median(mag[: int(fs * 5)]))
    frames = []
    step = int(fs * chunk_s); ov = int(fs * 150e-6)
    for s in range(0, len(mag), step):
        seg = mag[s: s + step + ov]
        if len(seg) < fs * 0.01:
            break
        frames += [(i + s, b, c) for i, b, c in find_frames(seg, fs, noise=noise)]
    planes = {}
    n_ok = n_df17 = 0
    for idx, bits, conf in frames:
        df = bits_to_int(bits, 0, 5)
        if df not in (17, 18):
            continue
        if not crc_check(bits):
            continue
        n_ok += 1; n_df17 += 1
        t = idx / fs
        icao = "%06X" % bits_to_int(bits, 8, 32)
        me = bits[32:88]
        tc = bits_to_int(me, 0, 5)
        p = planes.setdefault(icao, {"icao": icao, "msgs": 0, "callsign": "", "alt": None, "lat": None, "lon": None,
                                     "spd": None, "hdg": None, "vr": None, "vtype": "", "nopos": 0, "first": t, "last": t, "even": None, "odd": None})
        p["msgs"] += 1; p["last"] = t
        if 1 <= tc <= 4:
            p["callsign"] = decode_callsign(me)
        elif tc == 0:                                          # asukoht puudub (GNSS?), ainult kõrgus
            alt = decode_altitude(me)
            if alt is not None: p["alt"] = alt
            p["nopos"] = p.get("nopos", 0) + 1
        elif 9 <= tc <= 18:
            alt = decode_altitude(me)
            if alt is not None: p["alt"] = alt
            odd = me[21]
            cpr = (bits_to_int(me, 22, 39) / 131072.0, bits_to_int(me, 39, 56) / 131072.0)
            p["odd" if odd else "even"] = (cpr, t)
            pos = None
            if p["even"] and p["odd"] and abs(p["even"][1] - p["odd"][1]) < 10:
                pos = cpr_global(p["even"][0], p["odd"][0], p["even"][1], p["odd"][1])
            if pos is None:
                pos = cpr_local(cpr, odd)
                # lokaalne on usaldusväärne ainult ~180 NM raadiuses referentsist
                if abs(pos[0] - REF_LAT) > 3 or abs(pos[1] - REF_LON) > 6:
                    pos = None
            if pos:
                p["lat"], p["lon"] = round(pos[0], 4), round(pos[1], 4)
        elif tc == 19:
            v = decode_velocity(me)
            if v:
                p["spd"] = round(v[0]) if v[0] is not None else None
                p["hdg"] = round(v[1]) if v[1] is not None else None
                p["vr"], p["vtype"] = v[2], v[3]
    return planes, dict(dur=dur, candidates=len(frames), df17_ok=n_ok)


def dist_km(lat, lon):
    R = 6371
    p1, p2 = math.radians(REF_LAT), math.radians(lat)
    dl = math.radians(lon - REF_LON)
    a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    return 2 * R * math.asin(math.sqrt(a))


def write_svg(planes, path, span_km=250):
    W = 700; scale = W / (2 * span_km)
    def xy(lat, lon):
        dx = (lon - REF_LON) * 111.32 * math.cos(math.radians(REF_LAT)); dy = (lat - REF_LAT) * 111.32
        return W / 2 + dx * scale, W / 2 - dy * scale
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {W}" style="background:#2b2118;font-family:monospace">']
    for r in (50, 100, 150, 200):
        out.append(f'<circle cx="{W/2}" cy="{W/2}" r="{r*scale:.0f}" fill="none" stroke="#5a4636" stroke-dasharray="4 4"/>'
                   f'<text x="{W/2+r*scale+3:.0f}" y="{W/2-3}" fill="#8f8470" font-size="10">{r} km</text>')
    out.append(f'<text x="{W/2-20}" y="{W/2+14}" fill="#f2a900" font-size="11">EETN</text><circle cx="{W/2}" cy="{W/2}" r="3" fill="#f2a900"/>')
    for p in planes.values():
        if p["lat"] is None: continue
        x, y = xy(p["lat"], p["lon"])
        if not (0 <= x <= W and 0 <= y <= W): continue
        label = p["callsign"] or p["icao"]
        if p["alt"] is not None: label += f" {p['alt']}ft"
        rot = p["hdg"] or 0
        out.append(f'<g transform="translate({x:.0f},{y:.0f})"><polygon points="0,-7 5,6 0,3 -5,6" fill="#e8672b" transform="rotate({rot})"/>'
                   f'<text x="8" y="4" fill="#f3e9d2" font-size="11">{label}</text></g>')
    out.append("</svg>")
    open(path, "w", encoding="utf-8").write("\n".join(out))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("wav"); ap.add_argument("--csv"); ap.add_argument("--svg")
    a = ap.parse_args()
    t0 = time.time()
    planes, st = decode_file(a.wav)
    print(f"{os.path.basename(a.wav)}: {st['dur']:.0f} s, preambuleid {st['candidates']}, DF17 CRC ok {st['df17_ok']}, lennukeid {len(planes)}  ({time.time()-t0:.0f} s)")
    rows = sorted(planes.values(), key=lambda p: -p["msgs"])
    print(f"{'ICAO':7}{'kutsung':9}{'kõrgus ft':>10}{'lat':>9}{'lon':>9}{'km':>6}{'kn':>5}{'hdg':>5}{'ft/min':>8}{'sõn':>5}  kiirus  asukohata")
    for p in rows:
        km = f"{dist_km(p['lat'], p['lon']):.0f}" if p["lat"] is not None else ""
        print(f"{p['icao']:7}{p['callsign']:9}{(p['alt'] if p['alt'] is not None else ''):>10}{(p['lat'] if p['lat'] is not None else ''):>9}"
              f"{(p['lon'] if p['lon'] is not None else ''):>9}{km:>6}{(p['spd'] if p['spd'] is not None else ''):>5}{(p['hdg'] if p['hdg'] is not None else ''):>5}"
              f"{(p['vr'] if p['vr'] is not None else ''):>8}{p['msgs']:>5}  {p['vtype']:6}  {p['nopos']}")
    if a.csv:
        with open(a.csv, "w", newline="", encoding="utf-8") as f:
            wr = csv.writer(f); wr.writerow(["icao", "callsign", "alt_ft", "lat", "lon", "km", "kn", "hdg", "vrate", "msgs", "first_s", "last_s"])
            for p in rows:
                wr.writerow([p["icao"], p["callsign"], p["alt"], p["lat"], p["lon"], f"{dist_km(p['lat'], p['lon']):.0f}" if p["lat"] is not None else "",
                             p["spd"], p["hdg"], p["vr"], p["msgs"], f"{p['first']:.1f}", f"{p['last']:.1f}"])
    if a.svg:
        write_svg(planes, a.svg)


if __name__ == "__main__":
    main()
