#!/usr/bin/env python3
"""eeter-radio – raadio "mängija" taustateenusena + JSON API (TUI `eeter` ja teised kliendid).

Kuulamine käib SIIN (heli pipewire kaudu), klient on ainult pult: TUI sulgemine ei peata muusikat.
  FM : eeter-rx IQ (1234) -> fmstream (stereo) -> aplay;  RDS (iq.rds_decode) iga 2,5 s viimase 5 s pealt
  DAB: systemd eeter-dab@<kanal> (dab_rx.py + welle-cli :7979) -> mpv http://127.0.0.1:7979/mp3/<SId>
API (127.0.0.1:8090):
  GET  /api/status          olek (vt Radio.status)
  POST /api/mute            {"on": true|false} (ilma = lüliti) – kõlar vait, raadio (RDS, salvestus) töötab edasi
  POST /api/record          {"on": true|false} (ilma = lüliti) – salvesta, mida kuulad (music/<jaam>/…mp3 + .txt)
  GET  /api/stations        {"fm": [...], "dab": [...]}  (data/jaamad.json)
  POST /api/play            {"type":"fm","freq":101.6}  |  {"type":"dab","channel":"10D","sid":"0x2321"}
  POST /api/stop            vaikus (dongel jääb sinna, kus on)
  POST /api/scan            {"band":"fm"}  |  {"band":"dab","channels":["7B","10D"]}  ("all" = kogu Band III)
  WS   /api/live            olek 5 x sekundis
FM-jaam, mis mahub praegusesse 2,4 MHz aknasse (±1,0 MHz), kuulatakse ILMA tuunimata -> Raadio 2 salvesti jätkab.
"""
import asyncio, calendar, datetime as dt, json, os, re, socket, subprocess, sys, threading, time, urllib.request
from collections import deque
from pathlib import Path

import numpy as np
from aiohttp import web, WSMsgType

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import iq as iqlib
from fmstream import Ddc, FmStereo, AUDIO_FS

ROOT = Path(__file__).resolve().parent.parent
STATIONS = ROOT / "data" / "jaamad.json"
STATE = ROOT / "data" / "raadio_olek.json"          # {"station": ..., "recording": bool}
MUSIC = ROOT / "music"
FS = 2_400_000
WELLE = "http://127.0.0.1:7979"
FM_GAIN, DAB_GAIN = 33.8, 40.2
BAND3 = {  # ETSI EN 300 401 Band III kanalid (Hz)
    "5A": 174928000, "5B": 176640000, "5C": 178352000, "5D": 180064000, "6A": 181936000, "6B": 183648000, "6C": 185360000,
    "6D": 187072000, "7A": 188928000, "7B": 190640000, "7C": 192352000, "7D": 194064000, "8A": 195936000, "8B": 197648000,
    "8C": 199360000, "8D": 201072000, "9A": 202928000, "9B": 204640000, "9C": 206352000, "9D": 208064000, "10A": 209936000,
    "10B": 211648000, "10C": 213360000, "10D": 215072000, "11A": 216928000, "11B": 218640000, "11C": 220352000,
    "11D": 222064000, "12A": 223936000, "12B": 225648000, "12C": 227360000, "12D": 229072000, "13A": 230784000,
    "13B": 232496000, "13C": 234208000, "13D": 235776000, "13E": 237488000, "13F": 239200000}


def log(msg):
    print(f"[{dt.datetime.now():%H:%M:%S}] {msg}", flush=True)


def rig(*cmds):
    out = []
    with socket.create_connection(("127.0.0.1", 4532), timeout=3) as s:
        f = s.makefile("rw")
        for c in cmds:
            f.write(c + "\n"); f.flush()
            out.append(f.readline().strip())
    return out


def systemctl(*args):
    return subprocess.run(["systemctl", "--user", *args], capture_output=True, text=True).returncode


def welle_mux():
    try:
        with urllib.request.urlopen(WELLE + "/mux.json", timeout=2) as r:
            return json.load(r)
    except Exception:
        return None


def clean(label):
    return (label or "").strip().strip("'").strip()


def grab_iq(seconds):
    need = int(FS * seconds) * 4
    buf = bytearray(need); view = memoryview(buf); got = 0
    with socket.create_connection(("127.0.0.1", 1234), timeout=10) as s:
        while got < need:
            n = s.recv_into(view[got:], need - got)
            if not n: raise OSError("eeter-rx katkes")
            got += n
    d = np.frombuffer(buf, np.int16).astype(np.float32) / 32768
    return (d[0::2] + 1j * d[1::2]).astype(np.complex64)


def level_db(x):
    return float(20 * np.log10(np.sqrt(np.mean(np.square(x))) + 1e-9))


# ------------------------------------------------------------------ salvestus

def safe_name(s):
    return re.sub(r'[\\/:*?"<>|]+', "_", s or "").strip() or "tundmatu"


SLOGAN_RE = re.compile(r"www\.|\.ee\b|\.fi\b|\+372|whatsapp|telefon|helista|kuula|raadio\b|radio\b|fm\b|hetkel|eetris|"
                       r"uudised|reklaam|top ?\d|playlist|musiikki|hit music station", re.I)


def song_title(text, station):
    """RDS RT / DLS -> 'ARTIST - Pealkiri' kui see näeb välja nagu lugu (mitte slogan / jaama nimi), muidu None."""
    t = (text or "").replace("Hetkel eetris:", "").replace("Now playing:", "").strip().replace('"', "").replace("“", "").replace("”", "")
    if not t or "?" in t or " - " not in t or SLOGAN_RE.search(t):
        return None
    head = t.split(" - ", 1)[0].strip()
    if not head or len(head) > 60 or head.upper().replace(" ", "") == (station or "").upper().replace(" ", ""):
        return None
    return t


class Recording:
    """Salvesta, mida kuulad, LUGUDE KAUPA: music/<jaam>/<aeg> ARTIST - Pealkiri.mp3 (+ songs.csv, sessiooni lugude .txt).
    FM: sama PCM mis kõlarisse -> lame -V 2 (üks protsess faili kohta).  DAB: welle MP3-voog otse faili.
    Loo nimi (RT/DLS) tuleb hiljem kui loo algus -> DELAY s viivituspuhver: lõige tehakse DELAY s enne nime saabumist.
    Uus lugu = sama nimi kaks korda järjest. Mitte-lugu (saade, slogan) -> fail jaama nimega. < MIN_SONG s -> _short/."""
    DELAY = 8.0
    MIN_SONG = 45

    def __init__(self, name, kind, dab_url=None):
        self.name, self.kind = name, kind
        self.dir = MUSIC / safe_name(name)
        self.dir.mkdir(parents=True, exist_ok=True)
        self.t0 = time.time()
        self.txt = self.dir / f"{dt.datetime.now():%Y-%m-%d %H-%M-%S} {safe_name(name)} - lood.txt"
        self.buf = deque()                              # (aeg, baidid) – viivituspuhver
        self.lock = threading.Lock()
        self.stop_ev = threading.Event()
        self.cur = None
        self.last_text = self.pending = None
        self.pending_n = 0
        self._open(None)
        if kind == "dab":
            threading.Thread(target=self._pull, args=(dab_url,), daemon=True).start()
        log(f"salvestus algas: {self.name}")

    # ---- segmendid (üks fail = üks lugu)
    def _open(self, title):
        label = title or self.name
        path = self.dir / f"{dt.datetime.now():%Y-%m-%d %H-%M-%S} {safe_name(label)}.mp3"
        if self.kind == "fm":
            w = subprocess.Popen(["nice", "-n", "10", "lame", "--quiet", "-r", "-s", "48", "--bitwidth", "16", "--signed",
                                  "--little-endian", "-m", "j", "-V", "2", "-", str(path)],
                                 stdin=subprocess.PIPE, stderr=subprocess.DEVNULL)
        else:
            w = open(path, "wb")
        self.cur = {"path": path, "title": title, "w": w, "first": None, "last": None, "start": dt.datetime.now()}

    def _write(self, t, data):
        c = self.cur
        try:
            (c["w"].stdin if self.kind == "fm" else c["w"]).write(data)
        except (BrokenPipeError, OSError, ValueError):
            return
        c["first"] = c["first"] or t
        c["last"] = t

    def _finish(self, c):
        """Sulge fail (taustal – lame lõpetamine ei tohi heli kinni hoida), liiguta lühike _short/, kirjuta songs.csv."""
        def work():
            try:
                if self.kind == "fm":
                    c["w"].stdin.close(); c["w"].wait(15)
                else:
                    c["w"].close()
            except Exception as e:
                log(f"salvestus sulgemine: {e}")
            dur = (c["last"] - c["first"]) if c["first"] else 0
            path = c["path"]
            if dur < 1:
                path.unlink(missing_ok=True); return
            if c["title"] and dur < self.MIN_SONG or not c["title"] and dur < 5:
                short = self.dir / "_short"; short.mkdir(exist_ok=True)
                path = path.rename(short / path.name)
            csv_p = self.dir / "songs.csv"
            new = not csv_p.exists()
            with open(csv_p, "a", encoding="utf-8") as f:
                if new: f.write("algus,kestus_s,jaam,lugu,fail\n")
                title = (c["title"] or "").replace('"', "'")
                f.write(f'{c["start"]:%Y-%m-%d %H:%M:%S},{dur:.0f},"{self.name}","{title}","{path.relative_to(self.dir)}"\n')
            log(f"salvestatud: {path.relative_to(MUSIC)} ({dur:.0f} s)")
        threading.Thread(target=work, daemon=True).start()

    def _feed(self, data):
        now = time.time()
        with self.lock:
            self.buf.append((now, data))
            while self.buf and now - self.buf[0][0] > self.DELAY:
                self._write(*self.buf.popleft())

    def _split(self, title):
        with self.lock:                                   # puhver (viimased DELAY s) jääb -> läheb uue loo algusesse
            old, self.cur = self.cur, None
            self._open(title)
        self._finish(old)
        log(f"uus lugu: {title}")

    # ---- sisend
    def _pull(self, url):
        while not self.stop_ev.is_set():
            try:
                with urllib.request.urlopen(url, timeout=10) as r:
                    while not self.stop_ev.is_set():
                        b = r.read(8192)
                        if not b: break
                        self._feed(b)
            except Exception as e:
                log(f"DAB salvestus: {e}")
                self.stop_ev.wait(2)

    def write(self, pcm):                                # FM: 100 ms PCM plokid
        self._feed(pcm)

    def note(self, text):
        """RDS RT / DLS iga dekodeerimise järel (FM ~2,5 s, DAB 1 s)."""
        raw = (text or "").replace("Hetkel eetris: ", "").strip()
        if raw and raw != self.last_text:
            self.last_text = raw
            el = int(time.time() - self.t0)
            with open(self.txt, "a", encoding="utf-8") as f:
                f.write(f"{el // 3600:02d}:{el % 3600 // 60:02d}:{el % 60:02d}  {raw}\n")
        title = song_title(text, self.name)
        if not title:
            return
        self.pending_n = self.pending_n + 1 if title == self.pending else 1
        self.pending = title
        if self.pending_n >= 2 and title != self.cur["title"]:
            self._split(title)

    def close(self):
        self.stop_ev.set()
        with self.lock:
            while self.buf:
                self._write(*self.buf.popleft())
            c, self.cur = self.cur, self.cur
        self._finish(c)
        log(f"salvestus lõppes: {self.name} ({int(time.time() - self.t0)} s)")

    def info(self):
        c = self.cur or {}
        try: size = c["path"].stat().st_size
        except (OSError, KeyError): size = 0
        return {"file": str(c["path"].relative_to(MUSIC)) if c.get("path") else None, "seconds": int(time.time() - self.t0),
                "song_seconds": int(time.time() - c["first"]) if c.get("first") else 0, "mb": round(size / 1e6, 1),
                "title": c.get("title")}


# ------------------------------------------------------------------ FM

class FmEngine(threading.Thread):
    def __init__(self, freq_hz):
        super().__init__(daemon=True)
        self.freq = int(freq_hz)
        self.stop_ev = threading.Event()
        self.m = {"snr": None, "stereo": False, "pilot": 0.0, "audio_db": None, "center": None,
                  "rds": {"ps": "", "rt": "", "pty": None, "pi": None, "quality": None}}
        self.mpx = deque(maxlen=50)                    # 50 x 100 ms = 5 s
        self.clock = None                              # {"sig": UTC epoch signaalist, "wall": time.time() vastuvõtul, "source"}
        self.rds_busy = False
        self.rec = None                                # Recording (Radio paneb/võtab)
        self.muted = False                             # m: kõlarisse vaikus, kõik muu (RDS, salvestus) töötab

    def stop(self):
        self.stop_ev.set()

    def rds_job(self, mpx):
        try:
            r = iqlib.rds_decode(mpx * 75e3, 240e3)
            rd = self.m["rds"]
            if r.get("ok"):
                rd["quality"] = round(100 * r["blocks_valid"] / max(r["blocks_total"], 1))
                if r["ps"] and "?" not in r["ps"]: rd["ps"] = r["ps"].strip()
                if r["rt"] and r["rt"].count("?") <= 2:
                    rd["rt"] = r["rt"].strip()
                    rec = self.rec
                    if rec: rec.note(rd["rt"])
                if r["pty"]: rd["pty"] = r["pty"]
                if r["pi"] is not None: rd["pi"] = f"{r['pi']:04X}"
                ct = r.get("ct")                               # RDS 4A, kord minutis
                if ct and (not self.clock or self.clock["sig"] != ct["utc_epoch"]):
                    self.clock = {"sig": ct["utc_epoch"], "wall": time.time(), "source": "RDS"}
            else:
                rd["quality"] = 0
        except Exception as e:
            log(f"RDS viga: {e}")
        self.rds_busy = False

    def run(self):
        center = int(rig("f")[0])
        if abs(self.freq - center) > 1.0e6:
            rig(f"F {self.freq}", f"L RFGAIN {FM_GAIN}")
            center = self.freq
        self.m["center"] = center
        ddc, fm = Ddc(FS, self.freq - center), FmStereo()
        # 1 s puhver + 0,7 s vaikust ette: 100 ms plokkide ajastuse kõikumine (RDS-lõim, GIL) ei tee enam "underrun"-i
        aplay = subprocess.Popen(["aplay", "-q", "-r", str(AUDIO_FS), "-f", "S16_LE", "-c", "2", "-t", "raw",
                                  "--buffer-time=1000000", "--period-time=50000"], stdin=subprocess.PIPE)
        aplay.stdin.write(bytes(int(AUDIO_FS * 0.7) * 4))
        blk = FS // 10 * 4
        buf = bytearray(blk); view = memoryview(buf)
        last_rds = last_sig = 0
        try:
            s = socket.create_connection(("127.0.0.1", 1234), timeout=10)
            while not self.stop_ev.is_set():
                got = 0
                while got < blk:
                    n = s.recv_into(view[got:], blk - got)
                    if not n: raise OSError("eeter-rx katkes")
                    got += n
                d = np.frombuffer(buf, np.int16).astype(np.float32) / 32768
                x = (d[0::2] + 1j * d[1::2]).astype(np.complex64)
                ch = ddc(x)
                audio = fm(ch)
                self.mpx.append(fm.mpx_last)
                pcm = (np.clip(audio, -1, 1) * 32767).astype(np.int16).tobytes()
                aplay.stdin.write(bytes(len(pcm)) if self.muted else pcm)   # vaigistus: aplay jääb käima (ei tee underrun'i)
                rec = self.rec
                if rec: rec.write(pcm)
                now = time.time()
                if now - last_sig > 0.5:                   # tugevus: jaama ±75 kHz vs laia spektri mediaan
                    last_sig = now
                    X = np.abs(np.fft.fftshift(np.fft.fft(x[:65536]))) ** 2
                    f = np.fft.fftshift(np.fft.fftfreq(65536, 1 / FS))
                    off = self.freq - center
                    self.m["snr"] = round(float(10 * np.log10(X[np.abs(f - off) < 75e3].mean() / np.median(X))), 1)
                    self.m["pilot"] = round(fm.pilot_level, 3)
                    self.m["stereo"] = fm.pilot_level >= 0.01
                    self.m["audio_db"] = round(level_db(audio), 1)
                if now - last_rds > 2.5 and not self.rds_busy and len(self.mpx) >= 30:
                    last_rds = now; self.rds_busy = True
                    threading.Thread(target=self.rds_job, args=(np.concatenate(self.mpx),), daemon=True).start()
        except (OSError, BrokenPipeError) as e:
            log(f"FM: {e}")
        finally:
            try: aplay.stdin.close()
            except OSError: pass
            aplay.terminate()


# ------------------------------------------------------------------ DAB

class DabEngine(threading.Thread):
    def __init__(self, channel, sid):
        super().__init__(daemon=True)
        self.channel, self.sid = channel, sid
        self.stop_ev = threading.Event()
        self.clock = None
        self.rec = None
        self.muted = False
        self.m = {"ensemble": None, "snr": None, "fic_err_rate": None, "err_rate": None, "dls": "", "name": "",
                  "bitrate": None, "codec": None, "audio_db": None, "synced": False}

    def stop(self):
        self.stop_ev.set()

    def run(self):
        ensure_dab(self.channel)
        mpv = None; prev = None
        while not self.stop_ev.is_set():
            j = welle_mux()
            if j and j.get("services"):
                self.m["synced"] = True
                dem = j.get("demodulator", {})
                self.m["ensemble"] = clean(j["ensemble"]["label"]["label"])
                self.m["snr"] = dem.get("snr")
                fic = dem.get("fic", {}).get("numcrcerrors", 0)
                u = (j.get("utctime") or {})                   # FIG 0/10
                if u.get("year"):
                    sig = calendar.timegm((u["year"], u["month"], u["day"], u["hour"], u["minutes"], u.get("seconds", 0)))
                    if not self.clock or self.clock["sig"] != sig:
                        self.clock = {"sig": sig, "wall": time.time(), "source": "DAB"}
                svc = next((s for s in j["services"] if s["sid"] == self.sid), None)
                if svc:
                    ec = svc.get("errorcounters") or {}
                    err = ec.get("rserrors", 0) + ec.get("aacerrors", 0)
                    if prev:
                        dtt = time.time() - prev[0]
                        self.m["fic_err_rate"] = round((fic - prev[1]) / dtt, 1)
                        self.m["err_rate"] = round((err - prev[2]) / dtt, 1)
                    prev = (time.time(), fic, err)
                    self.m["name"] = clean(svc["label"]["label"])
                    self.m["dls"] = (svc.get("dls") or {}).get("label", "")
                    rec = self.rec
                    if rec: rec.note(self.m["dls"])
                    self.m["codec"] = svc.get("mode")
                    comp = (svc.get("components") or [{}])[0]
                    self.m["bitrate"] = (comp.get("subchannel") or {}).get("bitrate")
                    al = svc.get("audiolevel") or {}
                    if al: self.m["audio_db"] = round(20 * np.log10(max(abs(al.get("left", 0)), abs(al.get("right", 0))) / 32768 + 1e-9), 1)
                    if self.muted:                             # vaigistus: mängija kinni, welle + salvestus edasi
                        if mpv and mpv.poll() is None: mpv.terminate()
                    elif mpv is None or mpv.poll() is not None:
                        mpv = subprocess.Popen(["mpv", "--no-video", "--really-quiet", "--no-terminal", f"{WELLE}/mp3/{self.sid}"])
            else:
                self.m["synced"] = False
            self.stop_ev.wait(1.0)
        if mpv and mpv.poll() is None:
            mpv.terminate()


# ------------------------------------------------------------------ ADS-B (lennuside)

ADSB_DIR = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "eeter-adsb"


class AdsbEngine(threading.Thread):
    ACTIVE_S = 20                                      # "aktiivne" = signaal viimase 20 s jooksul (toas ~1–2 sõn/s lennuki kohta, vahed kuni ~15 s)
    """1090 MHz: dongel AGC-ga, eeter-rx rtl_tcp (1235, 12 B päis maha) -> readsb stdin (UC8 2,4 MSPS) -> aircraft.json iga 1 s.
    Heli pole; rec/muted/clock on ühilduvuse jaoks (Radio käsitleb kõiki mootoreid ühtemoodi)."""
    def __init__(self):
        super().__init__(daemon=True)
        self.stop_ev = threading.Event()
        self.rec = None; self.muted = False; self.clock = None
        self.m = {"aircraft": [], "count": 0, "with_pos": 0, "msg_rate": None, "messages": 0, "started": time.time(), "seen_total": 0,
                  "active_s": self.ACTIVE_S}
        self.reg = {}                                  # hex -> viimased andmed (jääb alles kogu sessiooni; readsb unustab ~5 min pärast)

    def stop(self):
        self.stop_ev.set()

    def run(self):
        rig("F 1090000000", "L RFGAIN auto")               # 1090: käsitsi gain andis müra (18.09), AGC toimib
        ADSB_DIR.mkdir(parents=True, exist_ok=True)
        rs = subprocess.Popen(["readsb", "--device-type", "ifile", "--ifile", "-", "--iformat", "UC8", "--quiet",
                               "--write-json", str(ADSB_DIR), "--write-json-every", "1"],
                              stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        def pump():
            try:
                with socket.create_connection(("127.0.0.1", 1235), timeout=10) as s:
                    s.recv(12)                                  # "RTL0" + tuuner + gain-astmed
                    while not self.stop_ev.is_set() and rs.poll() is None:
                        b = s.recv(262144)
                        if not b: break
                        rs.stdin.write(b)
            except (OSError, BrokenPipeError) as e:
                log(f"ADS-B voog: {e}")
        threading.Thread(target=pump, daemon=True).start()
        prev = None
        while not self.stop_ev.is_set():
            self.stop_ev.wait(1.0)
            try:
                j = json.loads((ADSB_DIR / "aircraft.json").read_text())
            except (OSError, ValueError):
                continue
            now = time.time()
            for a in j.get("aircraft", []):
                old = self.reg.get(a["hex"], {})
                self.reg[a["hex"]] = {**old, **a, "last_seen": now - a.get("seen", 0), "first_seen": old.get("first_seen", now)}
            ac = [dict(a, ago=round(now - a["last_seen"], 1)) for a in self.reg.values()]
            active = [a for a in ac if a["ago"] < self.ACTIVE_S]
            msgs = j.get("messages", 0)
            if prev:
                dtt = j.get("now", 0) - prev[0]
                if dtt > 0: self.m["msg_rate"] = round((msgs - prev[1]) / dtt, 1)
            prev = (j.get("now", 0), msgs)
            self.m.update(aircraft=ac, count=len(active), with_pos=sum("lat" in a for a in active), messages=msgs, seen_total=len(ac))
        try: rs.stdin.close()
        except OSError: pass
        rs.terminate()


def ensure_dab(channel):
    """eeter-dab@<kanal> käima (teised kanalid kinni); FM-kuulaja/salvesti vait, sest dongel läheb Band III peale."""
    unit = f"eeter-dab@{channel}"
    if systemctl("is-active", "--quiet", unit) != 0:
        systemctl("stop", "eeter-dab@*", "eeter-listen", "eeter-music")
        systemctl("start", unit)
    else:
        systemctl("stop", "eeter-listen")


def stop_dab():
    if subprocess.run("systemctl --user list-units --state=active --plain --no-legend 'eeter-dab@*' | grep -q .", shell=True).returncode == 0:
        systemctl("stop", "eeter-dab@*")


# ------------------------------------------------------------------ kontroller

class Radio:
    def __init__(self):
        self.engine = None
        self.station = None
        self.scan = None
        self.report = None                             # viimase skänni raport (jääb alles, kuni uus skänn)
        self.prev = None                               # jaam enne skänni -> POST /api/resume
        self.rec_on = False                            # r-nupp: salvesta, mida parajasti kuulad
        self.muted = False                             # m-nupp: kõlar vait, raadio töötab
        self.lock = threading.Lock()
        self.stations = self.load_stations()

    def load_stations(self):
        try: return json.loads(STATIONS.read_text())
        except (OSError, ValueError): return {"fm": [], "dab": []}

    def save_stations(self):
        STATIONS.write_text(json.dumps(self.stations, ensure_ascii=False, indent=1))

    def _save_state(self):
        STATE.write_text(json.dumps({"station": self.station, "recording": self.rec_on, "muted": self.muted}, ensure_ascii=False))

    def set_muted(self, on):
        with self.lock:
            self.muted = bool(on)
            if self.engine: self.engine.muted = self.muted
            self._save_state()
            log(f"kõlar {'VAIGISTATUD' if self.muted else 'sees'}")

    def _start_rec(self):
        e, st = self.engine, self.station
        if not (self.rec_on and e and st and e.rec is None): return
        if st["type"] == "adsb":
            return                                          # lennusides pole heli
        if st["type"] == "fm":
            e.rec = Recording(st.get("name") or f"FM {st['freq'] / 1e6:.1f}", "fm")
        else:
            e.rec = Recording(st.get("name") or st["sid"], "dab", f"{WELLE}/mp3/{st['sid']}")

    def _stop_rec(self):
        e = self.engine
        if e and e.rec:
            rec, e.rec = e.rec, None
            rec.close()

    def set_recording(self, on):
        with self.lock:
            self.rec_on = bool(on)
            self._save_state()
            if self.rec_on: self._start_rec()
            else: self._stop_rec()
            log(f"salvestus {'SEES' if self.rec_on else 'väljas'}")

    def _stop_engine(self):
        self._stop_rec()
        if self.engine:
            self.engine.stop(); self.engine.join(5)
            self.engine = None

    def play(self, req):
        with self.lock:
            if self.scan: raise ValueError("skännimine käib")
            self._stop_engine()
            if req["type"] == "fm":
                stop_dab()
                systemctl("stop", "eeter-listen")                  # vana kuulaja – muidu kaks heli korraga
                freq = int(round(float(req["freq"]) * 1e6)) if float(req["freq"]) < 1000 else int(req["freq"])
                name = next((s.get("name") for s in self.stations["fm"] if abs(s["freq"] - freq) < 50e3), "") or ""
                self.engine = FmEngine(freq)
                self.station = {"type": "fm", "freq": freq, "name": name}
            elif req["type"] == "adsb":
                stop_dab()
                systemctl("stop", "eeter-listen")
                self.engine = AdsbEngine()
                self.station = {"type": "adsb", "name": "ADS-B 1090 MHz"}
            elif req["type"] == "dab":
                ch, sid = req["channel"], req["sid"]
                name = req.get("name") or next((s["name"] for s in self.stations["dab"] if s["sid"] == sid), "")
                self.engine = DabEngine(ch, sid)
                self.station = {"type": "dab", "channel": ch, "sid": sid, "name": name}
            else:
                raise ValueError("type peab olema fm, dab või adsb")
            self.engine.muted = self.muted
            self.engine.start()
            self._start_rec()
            self._save_state()
            log(f"mängin {self.station}")

    def stop(self):
        with self.lock:
            self._stop_engine()
            self.station = None
            self._save_state()
            log("vait")

    # ---- skänn (eraldi lõimes)
    def start_scan(self, band, channels=None):
        with self.lock:
            if self.scan: raise ValueError("skännimine juba käib")
            self._stop_engine()
            if self.station: self.prev = self.station
            self.scan = {"band": band, "progress": 0.0, "msg": "algab", "found": 0, "log": []}
            self.scan_log = []
        threading.Thread(target=self._scan, args=(band, channels), daemon=True).start()

    def _slog(self, line):
        self.scan["log"] = (self.scan["log"] + [line])[-12:]           # elav vaade: viimased 12
        self.scan_log.append(line)                                     # raportisse: kõik
        log(f"skänn: {line}")

    def _scan(self, band, channels):
        self.station = None
        t0 = time.time()
        rep = {"band": band, "started": dt.datetime.now().isoformat(timespec="seconds"), "error": None}
        try:
            if band == "fm":
                rep.update(self._scan_fm())
            else:
                rep.update(self._scan_dab(channels))
            self.save_stations()
        except Exception as e:
            log(f"skänn: {e}")
            rep["error"] = str(e)
        finally:
            rep["seconds"] = round(time.time() - t0)
            rep["log"] = list(self.scan_log)
            self.report = rep
            self.scan = None
            if band == "dab":                              # dongel tagasi FM kodusagedusele (salvesti), aga EI mängi
                stop_dab(); rig("F 101600000", f"L RFGAIN {FM_GAIN}")

    def resume(self):
        if not self.prev: raise ValueError("eelmist jaama pole")
        self.play(self.prev)

    def _scan_fm(self):
        stop_dab()
        rig(f"L RFGAIN {FM_GAIN}")
        centers = [88.6e6 + i * 2.1e6 for i in range(10)]           # 87,5–108,0 MHz, kasutatav aken ±1,08 MHz
        found = {}
        known = {s["freq"]: s for s in self.stations.get("fm", [])}
        old = set(known)
        for i, c in enumerate(centers):
            self.scan.update(progress=i / len(centers), msg=f"{c / 1e6:.1f} MHz")
            rig(f"F {int(c)}"); time.sleep(0.3)
            x = grab_iq(3.0)
            rows, _ = iqlib.scan(x, FS, c, min_snr=12)
            for f, snr in rows:
                if not 87.5e6 <= f <= 108e6: continue
                ch, fs2 = iqlib.extract_channel(x, FS, f - c)          # tagastab (signaal, fs)
                r = iqlib.rds_decode(iqlib.fm_demod(ch, fs2), fs2)
                ps = r["ps"].strip() if r.get("ok") and r["ps"] and "?" not in r["ps"] else ""
                seen = found.get(int(f))                              # sama jaam kahes aknas -> tugevam jääb
                if not seen or snr > seen["snr"]:
                    found[int(f)] = {"freq": int(f), "name": ps or (seen or {}).get("name", ""), "snr": round(snr, 1),
                                     "pi": f"{r['pi']:04X}" if r.get("ok") and r.get("pi") is not None else None}
                self.scan["found"] = len(found)
            here = [s for s in found.values() if abs(s["freq"] - c) < 1.1e6]
            self._slog(f"{c / 1e6:5.1f} MHz aken: {len(rows)} jaama" + (f" ({', '.join(s['name'] for s in here if s['name'])[:50]})" if here else ""))
        # RDS ei jõua 3 s-ga nõrgalt jaamalt kohale -> nimi/PI eelmisest nimekirjast (sama sagedus või sama PI)
        by_pi = {s.get("pi"): s for s in known.values() if s.get("pi")}
        for st in found.values():
            k = known.get(st["freq"]) or by_pi.get(st.get("pi"))
            if k:
                if not st["name"]: st["name"] = k.get("name", "")
                if not st.get("pi"): st["pi"] = k.get("pi")
                if k.get("country"): st["country"] = k["country"]
        missing = [known[f] for f in sorted(old - set(found))]
        # nimekiri ei kahane (antenn võib olla hetkel teise ala jaoks): leidmata tuntud jaamad jäävad alles
        self.stations["fm"] = sorted([*found.values(), *missing], key=lambda s: s["freq"])
        self.stations["fm_scanned"] = dt.datetime.now().isoformat(timespec="seconds")
        rig("F 101600000")
        res = [dict(s, new=s["freq"] not in old) for s in sorted(found.values(), key=lambda s: -s["snr"])]
        return {"stations": res, "count": len(res), "new": sum(s["new"] for s in res),
                "missing": [{"freq": m["freq"], "name": m.get("name", "")} for m in missing]}

    def _scan_dab(self, channels):
        chans = list(BAND3) if channels in (None, "all", ["all"]) else channels
        systemctl("stop", "eeter-listen", "eeter-music")
        prev_dab = self.stations.get("dab", [])
        out = [s for s in prev_dab if s["channel"] not in chans]
        old = {s["sid"] for s in self.stations.get("dab", [])}
        chrep = []
        for i, ch in enumerate(chans):
            self.scan.update(progress=i / len(chans), msg=f"DAB {ch}")
            stop_dab(); systemctl("start", f"eeter-dab@{ch}")
            t0 = time.time(); j = None
            while time.time() - t0 < 25:
                time.sleep(2)
                j = welle_mux()
                if j and j.get("services") and all(clean(s["label"]["label"]) for s in j["services"]) and time.time() - t0 > 8:
                    break
            if j and j.get("services"):
                ens = clean(j["ensemble"]["label"]["label"])
                for s in j["services"]:
                    comp = (s.get("components") or [{}])[0]
                    out.append({"channel": ch, "ensemble": ens, "sid": s["sid"], "name": clean(s["label"]["label"]) or s["sid"],
                                "bitrate": (comp.get("subchannel") or {}).get("bitrate"), "snr": (j.get("demodulator") or {}).get("snr")})
                self.scan["found"] = len(out)
                snr = (j.get("demodulator") or {}).get("snr")
                names = [clean(s["label"]["label"]) or s["sid"] for s in j["services"]]
                chrep.append({"channel": ch, "ensemble": ens, "snr": snr, "services": sorted(names),
                              "new": sum(s["sid"] not in old for s in j["services"])})
                self._slog(f"{ch:>4}: {ens} – {len(names)} jaama, SNR {snr}")
            else:
                kept = [s for s in prev_dab if s["channel"] == ch]         # nimekiri ei kahane: vanad jäävad alles
                out.extend(kept)
                chrep.append({"channel": ch, "ensemble": None, "snr": None, "services": [], "new": 0, "kept": len(kept)})
                self._slog(f"{ch:>4}: tühi" + (f" (nimekirjas jäävad alles {len(kept)} varem leitud jaama)" if kept else ""))
        self.stations["dab"] = sorted(out, key=lambda s: (s["channel"], s["name"]))
        self.stations["dab_scanned"] = dt.datetime.now().isoformat(timespec="seconds")
        found = [c for c in chrep if c["ensemble"]]
        return {"channels": chrep, "count": sum(len(c["services"]) for c in found), "new": sum(c["new"] for c in found),
                "ensembles": len(found)}

    def status(self):
        e = self.engine
        st = {"time": time.time(), "muted": self.muted,
              "mode": "scan" if self.scan else (self.station["type"] if self.station else "off"),
              "station": self.station, "scan": dict(self.scan) if self.scan else None, "fm": None, "dab": None, "adsb": None,
              "report": self.report, "prev": self.prev}
        if isinstance(e, FmEngine):
            st["fm"] = json.loads(json.dumps(e.m))
            if st["fm"]["rds"]["ps"] and self.station and not self.station.get("name"):
                self.station["name"] = st["fm"]["rds"]["ps"]
        elif isinstance(e, AdsbEngine):
            st["adsb"] = dict(e.m)
        elif isinstance(e, DabEngine):
            st["dab"] = dict(e.m)
        c = getattr(e, "clock", None)                  # signaali kell, edasi loetud vastuvõtu hetkest
        st["clock"] = {"epoch": c["sig"] + (time.time() - c["wall"]), "source": c["source"]} if c else None
        rec = getattr(e, "rec", None)
        st["recorder"] = {"on": self.rec_on, "active": rec is not None, **(rec.info() if rec else {})}
        return st


# ------------------------------------------------------------------ HTTP / WS

def make_app(radio):
    app = web.Application()

    async def status(_):
        return web.json_response(radio.status())

    async def stations(_):
        return web.json_response(radio.stations)

    async def play(req):
        try:
            body = await req.json()
            await asyncio.to_thread(radio.play, body)
            return web.json_response({"ok": True, "station": radio.station})
        except (ValueError, KeyError, OSError) as e:
            return web.json_response({"ok": False, "error": str(e)}, status=400)

    async def resume(_):
        try:
            await asyncio.to_thread(radio.resume)
            return web.json_response({"ok": True, "station": radio.station})
        except (ValueError, KeyError, OSError) as e:
            return web.json_response({"ok": False, "error": str(e)}, status=400)

    async def record(req):
        body = await req.json() if req.can_read_body else {}
        on = body.get("on", not radio.rec_on)                 # ilma "on"-ita = lüliti
        await asyncio.to_thread(radio.set_recording, on)
        return web.json_response({"ok": True, "on": radio.rec_on})

    async def mute(req):
        body = await req.json() if req.can_read_body else {}
        await asyncio.to_thread(radio.set_muted, body.get("on", not radio.muted))
        return web.json_response({"ok": True, "on": radio.muted})

    async def stop(_):
        await asyncio.to_thread(radio.stop)
        return web.json_response({"ok": True})

    async def scan(req):
        try:
            body = await req.json()
            radio.start_scan(body.get("band", "fm"), body.get("channels"))
            return web.json_response({"ok": True})
        except ValueError as e:
            return web.json_response({"ok": False, "error": str(e)}, status=409)

    async def live(req):
        ws = web.WebSocketResponse(heartbeat=20)
        await ws.prepare(req)
        async def reader():
            async for msg in ws:
                if msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR): break
        rt = asyncio.create_task(reader())
        try:
            while not ws.closed:
                await ws.send_json(radio.status())
                await asyncio.sleep(0.2)
        except (ConnectionResetError, RuntimeError):
            pass
        rt.cancel()
        return ws

    app.add_routes([web.get("/api/status", status), web.get("/api/stations", stations), web.post("/api/play", play),
                    web.post("/api/stop", stop), web.post("/api/resume", resume), web.post("/api/record", record), web.post("/api/mute", mute), web.post("/api/scan", scan), web.get("/api/live", live)])
    return app


def main():
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8090)
    ap.add_argument("--resume", action="store_true", help="jätka viimase jaamaga (data/raadio_olek.json)")
    a = ap.parse_args()
    radio = Radio()
    if a.resume:
        try:
            last = json.loads(STATE.read_text())
            if last and "type" in last: last = {"station": last}          # vana formaat
            radio.rec_on = bool((last or {}).get("recording"))
            radio.muted = bool((last or {}).get("muted"))
            if last and last.get("station"): radio.play(last["station"])
        except (OSError, ValueError) as e:
            log(f"resume: {e}")
    log(f"eeter-radio API :{a.port}")
    web.run_app(make_app(radio), host="127.0.0.1", port=a.port, print=None)


if __name__ == "__main__":
    main()
