#!/usr/bin/env python3
"""FM-jaama kuulamine eeter-rx-ist (IQ 1234): stereo 48 kHz -> aplay (kõlar) või stdout.

  fm_listen.py [--station 101.6] [--tune] [--mono] [--gain 1.0] [--stdout]
--tune: tuuni eeter-rx jaamale (F). Muidu kuulab ainult siis, kui jaam on keskmest < 1.1 MHz (muidu vaikus).
systemd: ~/.config/systemd/user/eeter-listen.service (Raadio 2 kõlarist).
"""
import argparse, socket, subprocess, sys, time
import numpy as np
from fmstream import Ddc, FmStereo, AUDIO_FS


def rigctl(cmd, port=4532):
    try:
        with socket.create_connection(("127.0.0.1", port), timeout=2) as s:
            s.sendall((cmd + "\nq\n").encode())
            return s.makefile().readline().strip()
    except OSError:
        return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--station", type=float, default=101.6)
    ap.add_argument("--tune", action="store_true")
    ap.add_argument("--mono", action="store_true")
    ap.add_argument("--gain", type=float, default=1.0)
    ap.add_argument("--stdout", action="store_true", help="S16LE stereo 48k stdouti (aplay asemel)")
    ap.add_argument("--fs", type=int, default=2400000)
    a = ap.parse_args()
    f_st = int(round(a.station * 1e6))
    if a.tune:
        rigctl(f"F {f_st}")
    out = sys.stdout.buffer if a.stdout else subprocess.Popen(
        ["aplay", "-q", "-r", str(AUDIO_FS), "-f", "S16_LE", "-c", "2", "-t", "raw"], stdin=subprocess.PIPE).stdin
    blk = a.fs // 10 * 4                                     # 100 ms int16 I/Q
    while True:
        try:
            s = socket.create_connection(("127.0.0.1", 1234), timeout=10)
        except OSError as e:
            print(f"eeter-rx pole kättesaadav ({e}), proovin 3 s pärast", file=sys.stderr, flush=True)
            time.sleep(3); continue
        center, ddc, fm, last = None, None, None, 0
        buf = bytearray(blk); view = memoryview(buf)
        try:
            while True:
                got = 0
                while got < blk:
                    n = s.recv_into(view[got:], blk - got)
                    if not n: raise OSError("ühendus katkes")
                    got += n
                if time.time() - last > 2:
                    last = time.time()
                    try: c = int(rigctl("f"))
                    except (TypeError, ValueError): c = center
                    if c != center:
                        center = c
                        ddc = Ddc(a.fs, f_st - center) if abs(f_st - center) < 1.1e6 else None
                        fm = FmStereo(ddc.fs_out, mono=a.mono) if ddc else None
                        print(f"kese {center} Hz -> {'kuulan' if ddc else 'jaam väljas, vaikus'}", file=sys.stderr, flush=True)
                if ddc is None:
                    audio = np.zeros((AUDIO_FS // 10, 2), np.float32)
                else:
                    d = np.frombuffer(buf, np.int16).astype(np.float32) / 32768
                    audio = fm(ddc((d[0::2] + 1j * d[1::2]).astype(np.complex64)))
                out.write((np.clip(audio * a.gain, -1, 1) * 32767).astype(np.int16).tobytes())
                out.flush()
        except OSError as e:
            print(f"IQ: {e}", file=sys.stderr, flush=True)
            s.close(); time.sleep(1)


if __name__ == "__main__":
    main()
