"""NAVTEX / SITOR-B (FEC) dekooder kitsast IQ-st (satrec sat_navtex_*.wav, fs = 24 kHz, kanal 518 kHz keskel).
FSK 100 baud, nihe 170 Hz (mark = kandja −85 Hz, space = +85 Hz; NAVTEX: B = kõrgem sagedus? – proovime mõlemat polaarsust).
CCIR 476: 7 bitti, alati 4 ühte ja 3 nulli. Iga märk saadetakse kaks korda: DX ja 5 märki (350 ms) hiljem RX. Faasimärgid
RQ (DX) ja α (RX) sünkroniseerivad. Kasutus: python navtex.py sat_navtex_x.wav [--offset 0] [--invert] [--out fail.txt]
"""
import argparse, os, sys, wave
import numpy as np

# CCIR 476 (Wikipedia tabel, 2026-09-20 kontrollitud): 35 koodi, igaühes 4 ühte / 3 nulli. kood -> (tähed, numbrid)
CCIR476 = {
    0x47: ("A", "-"), 0x72: ("B", "?"), 0x1D: ("C", ":"), 0x53: ("D", "$"), 0x56: ("E", "3"), 0x1B: ("F", "!"), 0x35: ("G", "&"),
    0x69: ("H", "#"), 0x4D: ("I", "8"), 0x17: ("J", "'"), 0x1E: ("K", "("), 0x65: ("L", ")"), 0x39: ("M", "."), 0x59: ("N", ","),
    0x71: ("O", "9"), 0x2D: ("P", "0"), 0x2E: ("Q", "1"), 0x55: ("R", "4"), 0x4B: ("S", "'"), 0x74: ("T", "5"), 0x4E: ("U", "7"),
    0x3C: ("V", "="), 0x27: ("W", "2"), 0x3A: ("X", "/"), 0x2B: ("Y", "6"), 0x63: ("Z", "+"),
    0x5C: (" ", " "), 0x78: ("\r", "\r"), 0x6C: ("\n", "\n"), 0x6A: ("", ""),
}
FIGS, LTRS = 0x36, 0x5A
RQ, ALPHA, BETA = 0x33, 0x66, 0x0F        # SIB (faasimärk 1, DX), RPT (faasimärk 2, RX), SIA (idle)


def demod_fsk(iq, fs, baud=100.0, shift=170.0, offset=0.0):
    """Kaks toonifiltrit (mark/space) kandja ±shift/2 ümber, mähiste vahe → pehme bitt; sümbolikell energia järgi."""
    n = len(iq); t = np.arange(n) / fs
    fm = offset - shift / 2; fsp = offset + shift / 2
    bw = baud * 0.8
    def tone(fc):
        x = iq * np.exp(-2j * np.pi * fc * t)
        X = np.fft.fft(x); f = np.fft.fftfreq(n, 1 / fs); X[np.abs(f) > bw] = 0
        return np.abs(np.fft.ifft(X))
    soft = tone(fm) - tone(fsp)                      # >0 = mark (1)
    sps = fs / baud
    # sümbolikell: |diff| maksimum faasi järgi (Gardner-lihtsustus): otsi nihe, kus üleminekud on sümbolipiiril
    trans = np.abs(np.diff(soft)); nb = int(n / sps)
    phase = np.zeros(int(round(sps)))
    for k in range(len(phase)):
        idx = (np.arange(nb - 1) * sps + k).astype(int)
        phase[k] = trans[np.clip(idx, 0, len(trans) - 1)].sum()
    k0 = int(np.argmax(phase))                       # üleminekud on siin → sämpli keskkohas k0 + sps/2
    samp = (np.arange(nb) * sps + k0 + sps / 2).astype(int); samp = samp[samp < n]
    bits = (soft[samp] > 0).astype(np.uint8)
    snr = np.abs(soft[samp]).mean() / (np.std(soft[samp] - np.sign(soft[samp]) * np.abs(soft[samp]).mean()) + 1e-9)
    return bits, soft[samp]


def decode_bits(bits, invert=False, lsb_first=True):
    if invert:
        bits = 1 - bits
    n = len(bits)
    # märgisünkro: 7-bitine raam, kus 4 ühte ja 3 nulli ja DX/RX kordused (nihe 5 märki = 35 bitti) langevad kokku
    best = (-1, 0); bestcodes = []
    for ph in range(7):
        codes = []
        for i in range(ph, n - 7, 7):
            b = bits[i:i + 7]
            if lsb_first:
                b = b[::-1]
            codes.append(int("".join(map(str, b)), 2))
        ok = sum(1 for c in codes if bin(c).count("1") == 4)
        rep = sum(1 for i in range(len(codes) - 5) if codes[i] == codes[i + 5] and bin(codes[i]).count("1") == 4)
        score = ok + 3 * rep
        if score > best[0]:
            best = (score, ph); bestcodes = codes
    codes = bestcodes
    # FEC: võta DX; kui vigane, RX-koopia 5 märki hiljem
    out = []; figs = False; good = 0; bad = 0; phasing = 0
    for i in range(len(codes) - 5):
        c = codes[i]
        if bin(c).count("1") != 4:
            c = codes[i + 5]
            if bin(c).count("1") != 4:
                bad += 1; out.append("_"); continue
        good += 1
        if c == FIGS: figs = True; continue
        if c == LTRS: figs = False; continue
        if c in (RQ, ALPHA, BETA): phasing += 1; continue
        ch = CCIR476.get(c)
        if ch is None:
            out.append("·"); continue
        out.append(ch[1] if figs else ch[0])
    return "".join(out), good, bad, best[1], phasing


def main():
    ap = argparse.ArgumentParser(); ap.add_argument("wav"); ap.add_argument("--offset", type=float, default=0.0, help="kandja nihe Hz kanali keskmest")
    ap.add_argument("--invert", action="store_true"); ap.add_argument("--out"); ap.add_argument("--auto", action="store_true", help="otsi nihe ja polaarsus ise")
    ap.add_argument("--t0", type=float, default=0); ap.add_argument("--dur", type=float, default=0)
    a = ap.parse_args()
    try:
        with wave.open(a.wav, "rb") as w:
            fs = w.getframerate(); d = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float32) / 32768
        if len(d) < 1000:
            raise ValueError("päis pooleli")
    except Exception:
        # pooleli salvestus (päis veel lõpetamata): loe toorelt, fs failinimest või 24 kHz
        raw = np.fromfile(a.wav, np.int16, offset=44); d = raw.astype(np.float32) / 32768; fs = 24000
    iq = d[0::2] + 1j * d[1::2]
    if a.dur:
        iq = iq[int(a.t0 * fs): int((a.t0 + a.dur) * fs)]
    elif a.t0:
        iq = iq[int(a.t0 * fs):]
    print(f"{os.path.basename(a.wav)}: {len(iq)/fs:.0f} s, fs {fs} Hz")
    # spekter: kus on kaks tooni?
    N = 1 << 14; P = np.zeros(N); k = 0
    for s in range(0, len(iq) - N, N):
        P += np.abs(np.fft.fft(iq[s:s + N] * np.hanning(N))) ** 2; k += 1
    f = np.fft.fftfreq(N, 1 / fs); P = 10 * np.log10(P / max(k, 1) + 1e-12)
    m = np.abs(f) < 2000; top = f[m][np.argsort(P[m])[-6:]]
    print("tugevaimad toonid (Hz kanali keskmest):", np.round(np.sort(top)))
    cands = [a.offset] if not a.auto else sorted(set([round(float(t), 0) for t in top] + [a.offset]))
    results = []
    for off in cands:
        for o2 in ([off] if not a.auto else [off - 85, off + 85, off]):
            bits, soft = demod_fsk(iq, fs, offset=o2)
            for inv in ([a.invert] if not a.auto else [False, True]):
                for lsb in ([True] if not a.auto else [True, False]):
                    text, good, bad, ph, phasing = decode_bits(bits, inv, lsb)
                    results.append((good - 2 * bad, good, bad, phasing, o2, inv, lsb, text))
    results.sort(key=lambda r: r[0], reverse=True)
    _, good, bad, phasing, off, inv, lsb, text = results[0]
    print(f"parim: nihe {off:+.0f} Hz, invert={inv}, lsb_first={lsb}, märke OK {good}, vigaseid {bad}, faasimärke {phasing}")
    print(text)
    if a.out:
        open(a.out, "w", encoding="utf-8").write(text + "\n")


if __name__ == "__main__":
    main()
