"""Terve spektri läbikäik: 24 MHz – 1766 MHz 2 MHz sammuga (2,4 MHz aken, ülekattega) IQ Exporterist.
Iga sammu kohta keskmine PSD (4096-punktine FFT, 0,25 s), tulemus: captures/survey_<aeg>.npz + PNG + tugevaimate ribade tekst.
Kasutus: python survey.py [--from 24 --to 1766 --step 2] [--dwell 0.25] [--gain-note "37 dB"]
NB: peatab eelnevalt muusikasalvesti (Exporter on ühe-kliendi) – survey.ps1 teeb selle ise.
"""
import argparse, datetime as dt, os, socket, sys, time
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from music_recorder import rigctl
from specgram import write_png
from svgplot import Fig

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BANDS = [(0.5, 1.7, "keskklaine AM"), (1.8, 2.0, "160 m amatöörid"), (3.5, 3.8, "80 m amatöörid"), (3.9, 4.0, "75 m ringhääling"),
         (4.75, 5.06, "60 m ringhääling"), (5.9, 6.2, "49 m ringhääling"), (7.0, 7.2, "40 m amatöörid"), (7.2, 7.45, "41 m ringhääling"),
         (9.4, 9.9, "31 m ringhääling"), (10.1, 10.15, "30 m amatöörid"), (11.6, 12.1, "25 m ringhääling"), (13.57, 13.87, "22 m ringhääling"),
         (14.0, 14.35, "20 m amatöörid"), (15.1, 15.8, "19 m ringhääling"), (17.48, 17.9, "16 m ringhääling"), (18.07, 18.17, "17 m amatöörid"),
         (21.0, 21.45, "15 m amatöörid"), (21.45, 21.85, "13 m ringhääling"), (24.89, 24.99, "12 m amatöörid"), (25.67, 26.1, "11 m ringhääling"),
         (26.96, 27.41, "CB 27 MHz"), (28.0, 29.7, "10 m amatöörid"),
         (87.5, 108, "FM ringhääling"), (108, 118, "lennunavigatsioon VOR/ILS"), (118, 137, "lennuside AM"), (137, 138, "ilmasatelliidid"),
         (144, 146, "2 m amatöörid"), (146, 174, "mereside/POCSAG/mobiilne"), (174, 240, "DAB+ / VHF III"), (380, 400, "TETRA ESTER"),
         (400, 406, "raadiosondid"), (430, 440, "70 cm amatöörid / ISM 433"), (470, 694, "DVB-T2"), (703, 733, "LTE 700 üles"),
         (758, 788, "LTE 700 alla"), (791, 821, "LTE 800 alla"), (832, 862, "LTE 800 üles"), (863, 870, "ISM 868"),
         (880, 915, "GSM/LTE 900 üles"), (925, 960, "GSM/LTE 900 alla"), (1085, 1095, "ADS-B 1090"), (1164, 1215, "GNSS L5/L2"),
         (1227, 1228, "GPS L2"), (1452, 1492, "LTE L-band"), (1525, 1559, "Inmarsat alla"), (1559, 1610, "GNSS L1"),
         (1626, 1660, "Inmarsat üles"), (1690, 1710, "ilmasatelliidid HRPT"), (1710, 1785, "LTE 1800 üles")]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--from", dest="f0", type=float, default=24); ap.add_argument("--to", dest="f1", type=float, default=1766)
    ap.add_argument("--step", type=float, default=2.0); ap.add_argument("--dwell", type=float, default=0.25)
    ap.add_argument("--fs", type=int, default=2400000); ap.add_argument("--gain-note", default="")
    a = ap.parse_args()
    freqs = np.arange(a.f0, a.f1 + 0.001, a.step)
    N = 4096; nread = int(a.fs * a.dwell)
    win = np.hanning(N).astype(np.float32)
    fbin = np.fft.fftshift(np.fft.fftfreq(N, 1 / a.fs))
    keep = np.abs(fbin) <= a.step * 1e6 / 2 + 50e3          # ainult keskmine osa aknast (servad ülekattega)
    rows = []
    s = socket.create_connection(("127.0.0.1", 1234), timeout=10)
    t0 = time.time()
    print(f"läbikäik {a.f0}–{a.f1} MHz, {len(freqs)} sammu", flush=True)
    for i, f in enumerate(freqs):
        rigctl(f"F {int(f * 1e6)}")
        # tühjenda vana puhver (tuuneri ümberlülitus + Exporteri puhver)
        s.settimeout(2.0)
        need = int(a.fs * 0.35) * 4; buf = bytearray(need); view = memoryview(buf); got = 0
        while got < need:
            n = s.recv_into(view[got:], need - got)
            if not n:
                raise OSError("ühendus katkes")
            got += n
        buf = bytearray(nread * 4); view = memoryview(buf); got = 0
        while got < len(buf):
            n = s.recv_into(view[got:], len(buf) - got)
            if not n:
                raise OSError("ühendus katkes")
            got += n
        d = np.frombuffer(buf, np.int16).astype(np.float32) / 32768
        x = (d[0::2] + 1j * d[1::2])[: (nread // N) * N].reshape(-1, N) * win
        P = np.fft.fftshift(np.abs(np.fft.fft(x, axis=1)) ** 2, axes=1).mean(0)
        rows.append(10 * np.log10(P[keep] + 1e-12))
        if i % 50 == 0:
            print(f"  {f:6.0f} MHz  {time.time()-t0:5.0f} s  mediaan {np.median(rows[-1]):.1f} dB  max {rows[-1].max():.1f} dB", flush=True)
    s.close()
    S = np.array(rows)                                       # (nfreq, nbin)
    faxis = (freqs[:, None] * 1e6 + fbin[keep][None, :]).reshape(-1) / 1e6
    spec = S.reshape(-1)
    order = np.argsort(faxis); faxis, spec = faxis[order], spec[order]
    stamp = dt.datetime.now().strftime("%Y-%m-%d_%H%M")
    out = os.path.join(ROOT, "captures", f"survey_{stamp}")
    np.savez_compressed(out + ".npz", f=faxis, db=spec, gain=a.gain_note)
    # PNG: 1 px = 0,5 MHz veerg, kõrgus 200 px = dB skaala; tume = tugev
    W = int((a.f1 - a.f0) / 0.5); H = 220
    col = np.full(W, np.nan)
    idx = ((faxis - a.f0) / 0.5).astype(int); idx = np.clip(idx, 0, W - 1)
    for j in range(W):
        m = idx == j
        if m.any():
            col[j] = spec[m].max()
    floor = np.nanpercentile(col, 10); top = np.nanmax(col)
    img = np.full((H, W), 245, np.uint8)
    for j in range(W):
        if np.isfinite(col[j]):
            h = int((col[j] - floor) / max(top - floor, 1) * (H - 20)); h = max(0, min(H - 1, h))
            img[H - 1 - h:, j] = 40
    write_png(out + ".png", img)
    # tekst: ribade kaupa maksimum ja mediaan, pluss tugevaimad tipud
    lines = [f"Spektri läbikäik {stamp}, {a.f0}–{a.f1} MHz, samm {a.step} MHz, {a.dwell} s/samm, gain {a.gain_note}",
             f"müra põhi (10. protsentiil) {floor:.1f} dB, max {top:.1f} dB", "", "riba | max dB | mediaan dB | märkus"]
    for lo, hi, name in BANDS:
        m = (faxis >= lo) & (faxis < hi)
        if m.any():
            lines.append(f"{lo:7.1f}–{hi:7.1f} | {spec[m].max():6.1f} | {np.median(spec[m]):6.1f} | {name}")
    lines.append(""); lines.append("tugevaimad 0,5 MHz veerud:")
    order = np.argsort(col)[::-1]
    for j in order[:40]:
        if np.isfinite(col[j]):
            f = a.f0 + j * 0.5
            name = next((n for lo, hi, n in BANDS if lo <= f < hi), "?")
            lines.append(f"  {f:8.1f} MHz  {col[j]:6.1f} dB  {name}")
    open(out + ".txt", "w", encoding="utf-8").write("\n".join(lines))
    print("\n".join(lines[:35])); print(f"-> {out}.npz/.png/.txt  ({time.time()-t0:.0f} s)")


if __name__ == "__main__":
    main()
