#!/usr/bin/env python3
# Does the HR-C6000's inherited 0x34=0x3C (de-emphasis + 3 kHz low-pass) stop C4FM decoding?
# Standard C4FM through each audio stage, then the firmware demodulator and framer. Reproduces
# https://www.innerpulse.net/DEEPSEEKV41FLASH/   Run: DM1701_REPO=/path/to/DM-1701 python3 deemph_check.py
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import c4fm_sim as S  # noqa: E402

S.build_libs()
lib = S.load('rrc')
wire, wanted = S.build_stream(20, 1701)
base = S.tx_c4fm(wire)
out = []
for chain, label in (('', 'no audio filtering'), ('lpf3k', '3 kHz low-pass only'), ('deemph', 'de-emphasis only'),
                     ('deemph+lpf3k', 'de-emphasis + 3 kHz low-pass (0x34=0x3C)')):
    stages = S.rx_chain(chain) if chain else []
    row = {'chain': chain or 'none', 'label': label}
    for tag, snr in (('clean', None), ('snr20', 20)):
        y = S.add_noise(base, snr, 777)
        y = S.apply_chain(y, stages) if stages else y
        ref = S.apply_chain(base, stages) if stages else base
        y = y * (6000.0 / max(1.0, float(abs(ref).max())))
        fr, ni, dib, _ = S.decode(lib, y, len(wanted))
        e, t = S.raw_ser(dib, wire)
        row[tag] = {'frames': fr, 'nids': ni, 'ser': e / max(t, 1)}
    print(f"{label:45s} noise-free {row['clean']['frames']:3d}/180 frames, 20 dB {row['snr20']['frames']:3d}/180", flush=True)
    out.append(row)
json.dump(out, open(S.WORK / 'deemph_check.json', 'w'), indent=1)
