#!/usr/bin/env python3
"""
Tests for CW copy helpers backed by multimon-ng.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from ft991a.cw_copy import (
    CWCopyConfig,
    build_multimon_cw_command,
    normalize_multimon_text,
    parse_multimon_cw_line,
    score_copy_text,
)


def test_normalize_multimon_text_collapses_whitespace():
    assert normalize_multimon_text("  TNX   TO   MY   NEW   K3  ") == "TNX TO MY NEW K3"


def test_parse_multimon_copy_line():
    parsed = parse_multimon_cw_line(
        "2026-03-12 22:16:51: YS TNS TO MY NEW K3 ES HAD NO LUCK TRYING GET "
    )
    assert parsed == {
        "type": "copy",
        "timestamp": "2026-03-12 22:16:51",
        "text": "YS TNS TO MY NEW K3 ES HAD NO LUCK TRYING GET",
        "raw": "2026-03-12 22:16:51: YS TNS TO MY NEW K3 ES HAD NO LUCK TRYING GET",
    }


def test_parse_multimon_stats_line():
    parsed = parse_multimon_cw_line(
        "MAX: 8076 THRESHOLD: 5384 GLITCHES: 2 FAILED: 0 DECODED: 34 TIMING_GAP: 54 TIMING_DIT: 36"
    )
    assert parsed == {
        "type": "stats",
        "stats": {
            "max": 8076,
            "threshold": 5384,
            "glitches": 2,
            "failed": 0,
            "decoded": 34,
            "timing_gap": 54,
            "timing_dit": 36,
        },
        "raw": "MAX: 8076 THRESHOLD: 5384 GLITCHES: 2 FAILED: 0 DECODED: 34 TIMING_GAP: 54 TIMING_DIT: 36",
    }


def test_parse_multimon_stats_line_trims_embedded_timestamp():
    parsed = parse_multimon_cw_line(
        "MAX: 8076 THRESHOLD: 5384 GLITCHES: 2 FAILED: 0 DECODED: 34 TIMING_GAP: 54 TIMING_DIT: 362026-03-12 22:15:47:"
    )
    assert parsed == {
        "type": "stats",
        "stats": {
            "max": 8076,
            "threshold": 5384,
            "glitches": 2,
            "failed": 0,
            "decoded": 34,
            "timing_gap": 54,
            "timing_dit": 36,
        },
        "raw": "MAX: 8076 THRESHOLD: 5384 GLITCHES: 2 FAILED: 0 DECODED: 34 TIMING_GAP: 54 TIMING_DIT: 36",
    }


def test_score_copy_text_prefers_callsign_style_copy():
    assert score_copy_text("OK1DQP 5NN") > score_copy_text("<ERR_6> HHHH II")


def test_build_multimon_command_contains_validated_pipeline():
    config = CWCopyConfig(
        audio_device="hw:CARD=CODEC,DEV=0",
        sample_rate=22050,
        duration_sec=20,
        bandpass_low_hz=500,
        bandpass_high_hz=900,
        verbosity=1,
        auto_threshold=True,
        auto_timing=True,
    )

    command = build_multimon_cw_command(config)

    assert "set -o pipefail;" in command
    assert "arecord -D hw:CARD=CODEC,DEV=0" in command
    assert "-d 20" in command
    assert "sox -t raw -r 22050 -e signed-integer -b 16 -c 1 -" in command
    assert "sinc 500-900" in command
    assert "multimon-ng -t raw -a MORSE_CW --timestamp -v 1 -" in command
