"""CW ajastuse kontroll: sisse/välja kestuste histogramm (ms) ühe tooni kohta IQ-st. Kasutus: python cwdebug.py iq.wav 7.083 [--bw 40]"""
import argparse, os, sys
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from iq import load_iq, center_freq_from_name, extract_channel

ap = argparse.ArgumentParser(); ap.add_argument("wav"); ap.add_argument("mhz", type=float); ap.add_argument("--bw", type=float, default=40)
ap.add_argument("--thr", type=float, default=0.4)
a = ap.parse_args()
fc = center_freq_from_name(a.wav); fs, iq = load_iq(a.wav)
x, fs2 = extract_channel(iq, fs, int(round(a.mhz * 1e6)) - fc, out_fs=12e3)
n = len(x); f = np.fft.fftfreq(n, 1 / fs2)
Y = np.fft.fft(x); Y[np.abs(f) > a.bw] = 0; y = np.fft.ifft(Y)
env = np.abs(y); w = int(fs2 * 0.004); env = np.convolve(env, np.ones(w) / w, mode="same")
lo, hi = np.percentile(env, 20), np.percentile(env, 98); thr = lo + a.thr * (hi - lo)
print(f"mähis: p20 {lo:.4f} p50 {np.percentile(env,50):.4f} p98 {hi:.4f} lävi {thr:.4f}  (hi/lo {20*np.log10(hi/(lo+1e-9)):.0f} dB)")
on = env > thr; e = np.diff(np.concatenate([[0], on.astype(int), [0]])); st, en = np.where(e == 1)[0], np.where(e == -1)[0]
ons = (en - st) / fs2 * 1000; offs = (st[1:] - en[:-1]) / fs2 * 1000
def hist(v, name):
    bins = [0, 15, 30, 45, 60, 80, 100, 130, 170, 220, 300, 400, 600, 1000, 1e9]
    h, _ = np.histogram(v, bins); print(name, " ".join(f"{int(bins[i])}-{int(bins[i+1]) if bins[i+1] < 1e9 else 'inf'}:{h[i]}" for i in range(len(h)) if h[i]))
hist(ons, "SISSE ms"); hist(offs, "VÄLJA ms")
