"""Mereside analüüs pikast IQ-failist (kese 159,4 MHz): (1) aktiivsed kanalid airscan-iga 30 s tükkidena, (2) iga aktiivse
(või etteantud) kanali NFM-purskeklipp kokku, tükkhaaval laadides (180 s fail ei mahu korraga mällu).
Kasutus: python marine.py iq.wav [--chan 156.8,156.7] [--thr 8] [--top 6] [--out captures\meri]
Kanalite nimed: 156.300=06, 156.375=67, 156.450=09, 156.500=10, 156.525=70 DSC, 156.550=11, 156.600=12, 156.625=72, 156.650=13,
156.700=14, 156.725=74, 156.800=16, 156.875=77, 161.975=AIS1, 162.025=AIS2."""
import argparse, os, sys, wave
import numpy as np

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

NAMES = {156.300: "ch06", 156.375: "ch67", 156.450: "ch09", 156.500: "ch10", 156.525: "ch70 DSC", 156.550: "ch11", 156.600: "ch12",
         156.625: "ch72", 156.650: "ch13", 156.700: "ch14", 156.725: "ch74", 156.800: "ch16", 156.875: "ch77", 161.975: "AIS1", 162.025: "AIS2",
         157.100: "ch22", 156.425: "ch68", 156.475: "ch69", 156.575: "ch71", 156.675: "ch73", 156.825: "ch76"}


def name(mhz):
    for k, v in NAMES.items():
        if abs(k - mhz) < 0.006:
            return v
    return "x"


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("wav"); ap.add_argument("--chan", default="")
    ap.add_argument("--thr", type=float, default=8.0); ap.add_argument("--top", type=int, default=6); ap.add_argument("--out", default=None)
    ap.add_argument("--chunk", type=float, default=30.0)
    a = ap.parse_args()
    fc = iqlib.center_freq_from_name(a.wav)
    with wave.open(a.wav, "rb") as w:
        fs = w.getframerate(); total = w.getnframes() / fs
    print(f"{os.path.basename(a.wav)}: {total:.0f} s, kese {fc/1e6:.3f} MHz")
    # 1) aktiivsed kanalid
    found = {}
    if not a.chan:
        for st in np.arange(0, total, a.chunk):
            _, seg = iqlib.load_iq(a.wav, float(st), a.chunk)
            if len(seg) < fs:
                break
            chans_found, _dur = iqlib.airscan(seg, fs, fc, thresh_db=a.thr)
            for fr, frac, snr, bursts, exact, longest in chans_found:
                k = round(fr / 1e6 / 0.025) * 0.025          # 25 kHz raster
                d = found.setdefault(k, [0.0, 0.0, 0, 0.0])
                d[0] += frac * a.chunk; d[1] = max(d[1], snr); d[2] += bursts; d[3] = max(d[3], longest)
            del seg
        rows = sorted(found.items(), key=lambda kv: kv[1][0], reverse=True)
        print("aktiivsed kanalid (aktiivne s, max SNR, purskeid, pikim):")
        for k, (act, snr, b, lg) in rows[:20]:
            print(f"  {k:8.3f} MHz {name(k):>9}  {act:6.1f} s  {snr:5.1f} dB  {b:3d}  {lg:4.1f} s")
        chans = [k for k, _ in rows[:a.top] if k < 161.9]          # AIS ei ole hääl
    else:
        chans = [float(c) for c in a.chan.split(",")]
    # 2) NFM purskeklipid
    outdir = a.out or os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "captures", "meri")
    os.makedirs(outdir, exist_ok=True)
    stamp = os.path.basename(a.wav).split("Hz_")[1].replace(".wav", "")
    for ch in chans:
        xs = []
        for st in np.arange(0, total, a.chunk):
            _, seg = iqlib.load_iq(a.wav, float(st), a.chunk)
            if len(seg) < fs * 0.5:
                break
            x, fs2 = iqlib.extract_channel(seg, fs, ch * 1e6 - fc, out_fs=24e3); xs.append(x); del seg
        x = np.concatenate(xs)
        bl = int(fs2 * 0.05); nb = len(x) // bl
        S = np.abs(np.fft.fft(x[: nb * bl].reshape(nb, bl) * np.hanning(bl), axis=1)) ** 2
        fb = np.fft.fftfreq(bl, 1 / fs2); band = np.abs(fb) < 6000
        pw = 10 * np.log10(S[:, band].sum(axis=1) + 1e-12)
        on = pw > np.median(pw) + a.thr
        k = 8; on2 = np.convolve(on.astype(int), np.ones(2 * k + 1), "same") > 0
        ed = np.diff(np.concatenate([[0], on2.astype(int), [0]])); s0 = np.where(ed == 1)[0]; e0 = np.where(ed == -1)[0]
        ph = np.angle(x[1:] * np.conj(x[:-1])); audio = np.concatenate([[0], ph]) / (np.pi * 0.5)
        audio = audio - np.convolve(audio, np.ones(int(fs2 * 0.02)) / int(fs2 * 0.02), "same")
        A = np.fft.rfft(audio); f = np.fft.rfftfreq(len(audio), 1 / fs2); A[(f < 250) | (f > 3600)] = 0; audio = np.fft.irfft(A, len(audio))
        gap = np.zeros(int(fs2 * 0.3), np.float32); parts = []; tot = 0.0
        for s, e in zip(s0, e0):
            seg = audio[s * bl:e * bl]; seg = seg / (np.percentile(np.abs(seg), 99) + 1e-9) * 0.7
            parts += [seg.astype(np.float32), gap]; tot += len(seg) / fs2
        y = np.clip(np.concatenate(parts), -1, 1) if parts else np.zeros(1, np.float32)
        out = os.path.join(outdir, f"meri_{ch:.3f}_{name(ch).replace(' ', '')}_{stamp}.wav")
        with wave.open(out, "wb") as w:
            w.setnchannels(1); w.setsampwidth(2); w.setframerate(int(fs2)); w.writeframes((y * 32767).astype(np.int16).tobytes())
        print(f"{ch:.3f} {name(ch)}: {len(s0)} purset, {tot:.1f} s -> {out}")
        for s, e in list(zip(s0, e0))[:12]:
            print(f"    {s*0.05:6.1f}–{e*0.05:6.1f} s ({(e-s)*0.05:.1f} s) {pw[s:e].max()-np.median(pw):.0f} dB")


if __name__ == "__main__":
    main()
