"""Tests: the docs.md §13 test vectors byte for byte, then end-to-end behaviour."""

import inspect
import time
from typing import Annotated, NamedTuple

import pytest

import ufp
from ufp import f32, u8, u16, unit
from ufp.device import _Session
from ufp.types import Reader, Type
from ufp.wire import Deframer, cobs_decode, cobs_encode, crc16, frame

V = Annotated[f32, unit("V")]


class ReadAdc(NamedTuple):
    raw: u16
    voltage: V


def docs_board():
    """The example device of docs.md §13.1, declared with the public API."""
    dev = ufp.Device("SensorBoard", max_payload=128, max_inflight=1, log=False)
    dev.boot_id = 0x1234ABCD

    @dev.function
    def read_adc(channel: u8) -> ReadAdc:
        """Read one ADC channel"""
        return ReadAdc(2765, 3.325)

    @dev.function
    def set_led(id: u8, state: bool) -> None:
        pass

    @dev.function(returns="samples")
    def read_samples(channel: u8, count: u16) -> list[V]:
        """Burst-read samples"""
        return [1.5, -0.25][:count]

    @dev.event
    def threshold_exceeded(channel: u8, voltage: V):
        pass

    return dev, threshold_exceeded


# (request payload, response payload, response wire) from docs.md §13
VECTORS = [
    ("01 01",
     "81 01 04 03 01 80 00 01 CD AB 34 12 9B 14 87 9E 0B 53 65 6E 73 6F 72 42 6F 61 72 64",
     "07 81 01 04 03 01 80 18 01 CD AB 34 12 9B 14 87 9E 0B 53 65 6E 73 6F 72 42 6F 61 72 64 3A 51 00"),
    ("02 02 00",
     "82 02 00 08 72 65 61 64 5F 61 64 63 14 52 65 61 64 20 6F 6E 65 20 41 44 43 20 63 68 61 6E 6E 65 6C 01 02 07"
     " 63 68 61 6E 6E 65 6C 00 00 02 04 03 72 61 77 00 00 0A 07 76 6F 6C 74 61 67 65 00 01 56",
     "03 82 02 29 08 72 65 61 64 5F 61 64 63 14 52 65 61 64 20 6F 6E 65 20 41 44 43 20 63 68 61 6E 6E 65 6C 01 02"
     " 07 63 68 61 6E 6E 65 6C 01 07 02 04 03 72 61 77 01 0A 0A 07 76 6F 6C 74 61 67 65 05 01 56 1A 28 00"),
    ("02 04 02",
     "82 04 02 0C 72 65 61 64 5F 73 61 6D 70 6C 65 73 12 42 75 72 73 74 2D 72 65 61 64 20 73 61 6D 70 6C 65 73 02"
     " 02 07 63 68 61 6E 6E 65 6C 00 00 04 05 63 6F 75 6E 74 00 00 01 4A 07 73 61 6D 70 6C 65 73 00 01 56",
     "2E 82 04 02 0C 72 65 61 64 5F 73 61 6D 70 6C 65 73 12 42 75 72 73 74 2D 72 65 61 64 20 73 61 6D 70 6C 65 73"
     " 02 02 07 63 68 61 6E 6E 65 6C 01 08 04 05 63 6F 75 6E 74 01 0B 01 4A 07 73 61 6D 70 6C 65 73 05 01 56 C1 37"
     " 00"),
    ("03 05 00",
     "83 05 00 12 74 68 72 65 73 68 6F 6C 64 5F 65 78 63 65 65 64 65 64 00 02 02 07 63 68 61 6E 6E 65 6C 00 00 0A"
     " 07 76 6F 6C 74 61 67 65 00 01 56",
     "03 83 05 14 12 74 68 72 65 73 68 6F 6C 64 5F 65 78 63 65 65 64 65 64 0B 02 02 07 63 68 61 6E 6E 65 6C 01 0A"
     " 0A 07 76 6F 6C 74 61 67 65 05 01 56 51 4E 00"),
    ("05 06 00", "85 06 00", "03 85 06 03 90 B6 00"),
    ("04 07 00 03", "84 07 00 CD 0A CD CC 54 40", "03 84 07 09 CD 0A CD CC 54 40 E1 19 00"),
    ("04 08 01 00 01", "84 08 01", "06 84 08 01 8E B2 00"),
    ("04 09 02 03 02 00", "84 09 02 02 00 00 00 C0 3F 00 00 80 BE",
     "05 84 09 02 02 01 01 03 C0 3F 01 05 80 BE 4F 74 00"),
    ("04 0A 05", "FF 0A 04 02 10 75 6E 6B 6E 6F 77 6E 20 66 75 6E 63 74 69 6F 6E",
     "18 FF 0A 04 02 10 75 6E 6B 6E 6F 77 6E 20 66 75 6E 63 74 69 6F 6E B2 AF 00"),
    ("07 0B DE AD", "87 0B DE AD", "07 87 0B DE AD 4B AA 00"),
]
REQUEST_WIRE = {  # request payload -> wire, docs.md §13
    "01 01": "05 01 01 1F 3E 00",
    "02 02 00": "03 02 02 03 9E C4 00",
    "05 06 00": "03 05 06 03 CA 8D 00",
    "04 07 00 03": "03 04 07 04 03 C2 FB 00",
    "04 08 01 00 01": "04 04 08 01 04 01 D8 3A 00",
    "04 09 02 03 02 00": "06 04 09 02 03 02 03 97 72 00",
    "07 0B DE AD": "07 07 0B DE AD 73 77 00",
}
h = bytes.fromhex


class Capture:
    def __init__(self):
        self.out = []

    def write(self, data):
        self.out.append(data)


# ---------------------------------------------------------------------------
# wire-level vectors
# ---------------------------------------------------------------------------

def test_crc_check_values():
    assert crc16(b"123456789") == 0x29B1


def test_schema_hash_matches_docs():
    dev, _ = docs_board()
    assert dev.schema.hash == 0x9E87149B


@pytest.mark.parametrize("req,payload,wire", VECTORS)
def test_device_responses_match_docs(req, payload, wire):
    dev, _ = docs_board()
    session = _Session(dev, Capture())
    assert session.handle(h(req), dev.schema) == h(payload)
    assert frame(h(payload)) == h(wire)


@pytest.mark.parametrize("req,wire", REQUEST_WIRE.items())
def test_request_framing_matches_docs(req, wire):
    assert frame(h(req)) == h(wire)
    assert list(Deframer().feed(h(wire))) == [h(req)]


def test_event_notify_matches_docs():
    dev, threshold_exceeded = docs_board()
    out = Capture()
    session = _Session(dev, out)
    dev._sessions.add(session)
    session.handle(h("01 01"), dev.schema)
    threshold_exceeded(3, 3.325)          # not subscribed yet: nothing sent
    assert out.out == []
    session.handle(h("05 06 00"), dev.schema)
    threshold_exceeded(channel=3, voltage=3.325)
    assert out.out == [h("02 7F 01 08 03 CD CC 54 40 29 E5 00")]


# ---------------------------------------------------------------------------
# framing and types
# ---------------------------------------------------------------------------

@pytest.mark.parametrize("n", [0, 1, 253, 254, 255, 508, 1000])
def test_cobs_roundtrip(n):
    data = bytes((i * 7) % 256 for i in range(n))
    enc = cobs_encode(data)
    assert 0 not in enc and cobs_decode(enc) == data


def test_deframer_resyncs_after_noise_and_bad_crc():
    good = frame(b"\x07\x01")
    bad = bytearray(frame(b"\x07\x02"))
    bad[2] ^= 0xFF
    d = Deframer(max_payload=64)
    stream = b"\x13\x37garbage\x00" + bytes(bad) + b"\x00\x00" + b"\xAA" * 500 + b"\x00" + good
    assert list(d.feed(stream[:10])) == []
    assert list(d.feed(stream[10:])) == [b"\x07\x01"]
    assert d.errors == 3


@pytest.mark.parametrize("text", ["bool", "u8", "i64", "f64", "str", "bytes", "f32[]", "u8[16]"])
def test_type_roundtrip(text):
    t = Type.parse(text)
    assert str(t) == text
    assert Type.read(Reader(t.describe())) == t


def test_value_packing():
    t = Type.parse("u16[3]")
    out = bytearray()
    t.pack([1, 2, 3], out)
    assert bytes(out) == h("01 00 02 00 03 00")
    with pytest.raises(ValueError):
        t.pack([1, 2], bytearray())
    with pytest.raises(ufp.Malformed):
        Type.parse("bool").unpack(Reader(b"\x02"))
    with pytest.raises(ValueError):
        Type.parse("str[]")


# ---------------------------------------------------------------------------
# end to end, in-process
# ---------------------------------------------------------------------------

@pytest.fixture
def board():
    dev = ufp.Device("TestBoard")
    leds = [False] * 4

    @dev.function
    def read_adc(channel: u8) -> ReadAdc:
        """Read one ADC channel"""
        return ReadAdc(channel * 100, channel * 0.5)

    @dev.function
    def set_led(led: u8, on: bool) -> None:
        leds[led] = on

    @dev.function
    def echo(text: str, data: bytes, values: list[float]) -> tuple[str, bytes, list[float]]:
        return text, data, values

    @dev.function
    def fail(code: u8) -> None:
        raise ufp.RemoteError(code, "custom failure")

    @dev.function
    def slow(seconds: float) -> None:
        time.sleep(seconds)

    @dev.event
    def tick(n: u16):
        """Periodic tick"""

    @dev.function
    def fire(n: u16) -> None:
        for i in range(n):
            tick(i)
        dev.log("fired", "debug")

    with ufp.connect(dev) as client:
        yield client


def test_calls(board):
    assert board.read_adc(3) == (300, 1.5)
    r = board.read_adc(channel=2)
    assert (r.raw, r.voltage) == (200, 1.0)
    assert board.set_led(1, True) is None
    assert board.echo("héllo", b"\x00\x01", [1.5, 2.5]) == ("héllo", b"\x00\x01", [1.5, 2.5])
    assert board.call("read_adc", 1).raw == 100
    assert board.call(0, 1).raw == 100


def test_introspection(board):
    assert str(inspect.signature(board.read_adc)) == "(channel: u8) -> (raw: u16, voltage: f32 [V])"
    assert "Read one ADC channel" in board.read_adc.__doc__
    assert "read_adc" in dir(board)
    assert "read_adc(channel: u8)" in board.describe()
    assert board.info.name == "TestBoard"


def test_errors(board):
    with pytest.raises(ufp.RemoteError) as e:
        board.set_led(9, True)                  # IndexError on the device
    assert e.value.code == ufp.Err.EXEC_FAILED and "IndexError" in e.value.message
    with pytest.raises(ufp.RemoteError) as e:
        board.fail(0x81)
    assert e.value.code == 0x81 and e.value.message == "custom failure"
    with pytest.raises(TypeError):
        board.read_adc(1, 2)                    # caught locally
    with pytest.raises(TypeError):
        board.read_adc(300)                     # out of range for u8
    with pytest.raises(AttributeError):
        board.nope()


def test_timeout_then_recovers(board):
    with pytest.raises(ufp.Timeout):
        board.slow.call(0.3, timeout=0.05)
    time.sleep(0.4)
    assert board.read_adc(1).raw == 100        # late response was ignored


def test_events(board):
    got = []

    logs = []
    board.on("log", lambda level, msg: logs.append((level, msg)))

    @board.on("tick")
    def handler(n):
        got.append(n)

    board.fire(5)
    deadline = time.time() + 1
    while (len(got) < 5 or not logs) and time.time() < deadline:
        time.sleep(0.01)
    assert got == [0, 1, 2, 3, 4]
    assert logs == [(3, "fired")]
    assert board.dropped == 0

    board.off("tick")
    board.fire(2)
    time.sleep(0.1)
    assert got == [0, 1, 2, 3, 4]


def test_wait(board):
    import threading
    threading.Timer(0.05, board.fire, args=(1,)).start()
    assert board.wait("tick", timeout=1) == (0,)
    with pytest.raises(ufp.Timeout):
        board.wait("tick", timeout=0.05)


def test_schema_file(board, tmp_path):
    path = tmp_path / "board.json"
    board.schema.save(path)
    assert ufp.Schema.load(path).hash == board.info.schema_hash

    dev = ufp.Device("Other")

    @dev.function
    def f(x: u8) -> u8:
        return x

    with pytest.raises(ufp.UfpError, match="schema mismatch"):
        ufp.connect(dev, schema=path)


def test_registration_errors():
    dev = ufp.Device("X")
    with pytest.raises(TypeError, match="annotation"):
        @dev.function
        def f(x):
            pass
    with pytest.raises(ValueError, match="invalid UFP name"):
        dev.function(lambda: None)
