"""CW (morse) dekooder helifailist (SSB-demoduleeritud *_usb/_lsb.wav) või IQ-st.
Leiab tugevaima kitsa tooni 300–2900 Hz, filtreerib ±60 Hz, mähisjoon, adaptiivne lävi, sisse/välja kestused →
punkt/kriips/vahe klasterdamine (punkt = lühikeste mediaan) → tähed. Trükib kiiruse (WPM) ja teksti.
Kasutus: python cw.py heli.wav [--tone 700] [--out fail.txt]
"""
import argparse, wave
import numpy as np

MORSE = {".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J",
         "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T",
         "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "-----": "0", ".----": "1", "..---": "2",
         "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", ".-.-.-": ".",
         "--..--": ",", "..--..": "?", "-..-.": "/", "-...-": "=", ".-.-.": "+", "-.--.": "(", "-.--.-": ")", ".-...": "&",
         "---...": ":", ".----.": "'", "-....-": "-", ".-..-.": '"', ".--.-.": "@", "...-.-": "<SK>", "-.-.-": "<KA>", "........": "<err>"}


def decode(x, fs, tone=None, verbose=True):
    n = len(x)
    X = np.fft.rfft(x * np.hanning(n)); f = np.fft.rfftfreq(n, 1 / fs)
    if tone is None:
        m = (f > 300) & (f < 2900)
        # kitsas tipp: võrdle 20 Hz akna võimsust ±300 Hz ümbrusega
        P = np.abs(X) ** 2
        sm = np.convolve(P, np.ones(int(20 / (f[1] - f[0])) + 1), mode="same")
        wide = np.convolve(P, np.ones(int(600 / (f[1] - f[0])) + 1), mode="same") + 1e-12
        cand = np.where(m)[0]; tone = f[cand[np.argmax(sm[cand] / wide[cand])]]
    Y = np.fft.rfft(x); Y[np.abs(f - tone) > 60] = 0
    a = np.fft.irfft(Y, n)
    env = np.abs(a + 1j * np.imag(np.fft.ifft(np.fft.fft(a) * (2 * (np.fft.fftfreq(n) > 0)))))   # analüütiline mähis
    w = max(1, int(fs * 0.004)); env = np.convolve(env, np.ones(w) / w, mode="same")
    lo, hi = np.percentile(env, 20), np.percentile(env, 98)
    thr = lo + 0.4 * (hi - lo)
    on = env > thr
    # silu: ON-välgatused < 15 ms maha, OFF-augud < 10 ms täis (muidu lõhuvad nad tähevahed pooleks)
    for min_len, val in ((int(fs * 0.015), False), (int(fs * 0.010), True)):
        edges = np.diff(np.concatenate([[0], (on == (not val)).astype(int), [0]]))
        s, e = np.where(edges == 1)[0], np.where(edges == -1)[0]
        for i, j in zip(s, e):
            if j - i < min_len:
                on[i:j] = val
    edges = np.diff(np.concatenate([[0], on.astype(int), [0]]))
    st, en = np.where(edges == 1)[0], np.where(edges == -1)[0]
    if len(st) < 5:
        return tone, 0, "", []
    ons = (en - st) / fs
    # punkti pikkus: lühemate märkide klaster (k-means 2 klastrit log-skaalal)
    lg = np.log(ons); c = np.array([lg.min(), lg.max()])
    for _ in range(20):
        lab = np.abs(lg[:, None] - c[None, :]).argmin(1)
        c = np.array([lg[lab == k].mean() if (lab == k).any() else c[k] for k in range(2)])
    dot = float(np.exp(c[0])); dash_thr = dot * 2.0
    wpm = 1.2 / dot
    out = []; sym = ""; items = []
    for i in range(len(st)):
        d = (en[i] - st[i]) / fs
        sym += "-" if d > dash_thr else "."
        gap = (st[i + 1] - en[i]) / fs if i + 1 < len(st) else 99
        if gap > dot * 2.2:                          # tähevahe (nominaal 3 punkti; elemendivahe 1)
            items.append(sym); out.append(MORSE.get(sym, "¿" + sym + "?")); sym = ""
            if gap > dot * 5.5:                      # sõnavahe (nominaal 7)
                out.append(" ")
    text = "".join(out)
    return tone, wpm, text, items


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("wav"); ap.add_argument("--tone", type=float); ap.add_argument("--out")
    a = ap.parse_args()
    with wave.open(a.wav, "rb") as w:
        fs = w.getframerate(); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768
    tone, wpm, text, items = decode(x, fs, a.tone)
    print(f"toon {tone:.0f} Hz, kiirus ~{wpm:.0f} WPM, {len(items)} märki")
    print(text)
    if a.out:
        open(a.out, "w", encoding="utf-8").write(f"toon {tone:.0f} Hz, {wpm:.0f} WPM\n{text}\n" + " ".join(items) + "\n")
