"""Satelliidi ülelennu salvestus: SDR++ IQ Exporter (2.4 MSPS) -> jooksev dekimeerimine -> kitsas IQ WAV.
Ei salvesta täismahus (15 min 2.4 MSPS = 8.6 GB), vaid ±out_fs/2 kanali satelliidi sageduse ümber.

Kasutus: python satrec.py --mhz 137.9 --seconds 900 [--bw 250000] [--name meteor_m2_3]
NB: IQ Exporter on ühe-kliendi server -> muusikasalvesti peab olema peatatud (music.ps1 stop) ja SDR++ tuunitud --mhz peale
(skript teeb rigctl F ise). Väljund: recordings/sat_<name>_<Hz>Hz_<aeg>.wav (int16 I/Q, samplerate = bw).
"""
import argparse, datetime as dt, os, queue, socket, sys, threading, time, wave
from pathlib import Path
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import iq as iqlib
from music_recorder import rigctl

ROOT = Path(__file__).resolve().parent.parent


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mhz", type=float, required=True); ap.add_argument("--seconds", type=int, default=900)
    ap.add_argument("--bw", type=float, default=250e3); ap.add_argument("--name", default="sat")
    ap.add_argument("--fs", type=int, default=2400000); ap.add_argument("--port", type=int, default=1234)
    ap.add_argument("--channels", default="", help="mitu kanalit korraga, MHz komadega (nt 137.1,137.9); --mhz on siis tuuneri kese")
    a = ap.parse_args()
    f_hz = int(round(a.mhz * 1e6))
    rigctl(f"F {f_hz}"); time.sleep(1)
    center = int(rigctl("f")[0])
    chans = [int(round(float(m) * 1e6)) for m in a.channels.split(",") if m.strip()] or [f_hz]
    stamp = f"{dt.datetime.now():%H-%M-%S_%d-%m-%Y}"
    outs = [ROOT / "recordings" / f"sat_{a.name}_{ch}Hz_{stamp}.wav" for ch in chans]
    ws = []
    for o in outs:
        w = wave.open(str(o), "wb"); w.setnchannels(2); w.setsampwidth(2); w.setframerate(int(a.bw)); ws.append(w)
    out = outs[0]
    block_s = 2.0; need = int(a.fs * block_s) * 4
    print(f"salvestan {a.name} kese {center/1e6:.3f} MHz, kanalid {[c/1e6 for c in chans]}, {a.seconds} s -> {[o.name for o in outs]}", flush=True)
    t_end = time.time() + a.seconds; n_blocks = 0; peak_db = []
    # Lugeja eraldi lõimes: Exporter viskab sämpleid minema, kui klient ei loe pidevalt (varem kadus ~30 % ajast
    # dekimeerimise ajal). recv ja numpy FFT vabastavad GIL-i, nii et lugemine ja töötlus käivad päriselt kõrvuti.
    q = queue.Queue(maxsize=60)

    def reader():
        s = None
        while time.time() < t_end:
            try:
                if s is None:
                    s = socket.create_connection(("127.0.0.1", a.port), timeout=15)
                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
                try:
                    q.put(buf, timeout=5)
                except queue.Full:
                    print("  töötlus ei jõua järele – plokk visati minema", flush=True)
            except OSError as e:                              # Exporteri hikk -> ühendu uuesti, ära lõpeta
                print(f"  ühendus: {e} – taasühendun", flush=True)
                try:
                    if s: s.close()
                except OSError: pass
                s = None; time.sleep(2)
        if s: s.close()
        q.put(None)

    th = threading.Thread(target=reader, daemon=True); th.start()
    try:
        while True:
            buf = q.get()
            if buf is None:
                break
            d = np.frombuffer(buf, dtype=np.int16).astype(np.float32) / 32768.0
            x = (d[0::2] + 1j * d[1::2]).astype(np.complex64)
            for ch, w in zip(chans, ws):
                y, fs2 = iqlib.fft_decimate_complex(x, a.fs, ch - center, a.bw)
                y = np.clip(y * 4.0, -1, 1)                  # natuke võimendust int16 jaoks
                inter = np.empty(2 * len(y), dtype=np.int16)
                inter[0::2] = (y.real * 32767).astype(np.int16); inter[1::2] = (y.imag * 32767).astype(np.int16)
                w.writeframes(inter.tobytes())
            n_blocks += 1
            P = np.abs(np.fft.fft(y[: 8192] * np.hanning(8192))) ** 2
            peak_db.append(10 * np.log10(P.max() / np.median(P) + 1e-12))
            if n_blocks % 15 == 0:
                print(f"  {n_blocks*block_s:5.0f} s  tipp/mediaan {peak_db[-1]:5.1f} dB", flush=True)
    finally:
        for w in ws:
            w.close()
        for o in outs:
            print(f"valmis: {o} ({o.stat().st_size/1e6:.0f} MB), max tipp/mediaan {max(peak_db) if peak_db else 0:.1f} dB", flush=True)


if __name__ == "__main__":
    main()
