"""Tests for the test/dev packet-builder helpers.

These wrap raw bytes; the real validation that they produce protocol-
correct output is the round-trip via :func:`decode_avl_packet`.
"""

from __future__ import annotations

from mgf.tele.teltonika import (
    CODEC_8,
    CODEC_8_EXTENDED,
    decode_avl_packet,
)
from mgf.tele.teltonika._packets import (
    build_codec8_record,
    build_codec8e_record,
    handshake_bytes,
    wrap_codec8_envelope,
    wrap_codec8e_envelope,
)


def test_handshake_bytes_emits_2byte_length_prefix_and_ascii() -> None:
    out = handshake_bytes("356307042441013")
    assert out[:2] == (15).to_bytes(2, "big")
    assert out[2:] == b"356307042441013"


def test_handshake_bytes_round_trips_arbitrary_imei_lengths() -> None:
    for imei in ("12345678901234", "1234567890123456"):  # 14 + 16
        out = handshake_bytes(imei)
        assert int.from_bytes(out[:2], "big") == len(imei)
        assert out[2:].decode("ascii") == imei


def test_codec8_packet_round_trips_through_decoder() -> None:
    record = build_codec8_record(
        ts_ms=1_700_000_000_000,
        priority=1,
        lon_raw=int(44.3661 * 1e7),
        lat_raw=int(33.3152 * 1e7),
        alt=34,
        angle=180,
        satellites=12,
        speed=42,
        inputs_1b={239: 1, 240: 1},
    )
    packet = wrap_codec8_envelope([record])
    codec_id, decoded = decode_avl_packet(packet)
    assert codec_id == CODEC_8
    assert len(decoded) == 1
    assert decoded[0].codec == "C8"
    assert decoded[0].satellites == 12
    assert decoded[0].inputs == {239: 1, 240: 1}


def test_codec8_packet_with_multiple_records_decodes_in_order() -> None:
    records = [build_codec8_record(ts_ms=i * 1000, satellites=i) for i in range(5)]
    packet = wrap_codec8_envelope(records)
    _, decoded = decode_avl_packet(packet)
    assert [r.satellites for r in decoded] == [0, 1, 2, 3, 4]


def test_codec8e_packet_round_trips_through_decoder() -> None:
    record = build_codec8e_record(
        ts_ms=1_700_000_000_000,
        inputs_2b={1234: 0xABCD, 5678: 0x1111},
    )
    packet = wrap_codec8e_envelope([record])
    codec_id, decoded = decode_avl_packet(packet)
    assert codec_id == CODEC_8_EXTENDED
    assert decoded[0].codec == "C8E"
    assert dict(decoded[0].inputs) == {1234: 0xABCD, 5678: 0x1111}


def test_codec8e_packet_nx_section_validates_in_decoder() -> None:
    """NX entries get layout-validated by the decoder; the inputs map stays intact."""
    record = build_codec8e_record(
        ts_ms=0,
        inputs_2b={42: 7},
        nx_entries=[(9999, b"\x01\x02\x03")],
    )
    packet = wrap_codec8e_envelope([record])
    _, decoded = decode_avl_packet(packet)
    assert dict(decoded[0].inputs) == {42: 7}
