"""Transponder v1 activity-light example. Python 3; standard library only.

Bind identity() to your authenticated Control read. After bonding and enabling
Status notifications, pass each Control write to receive(). Send any returned
packet on Status using status_fragments() and the negotiated value limit. Call disconnect() on unsubscribe or disconnect. Bind working
and unread to your indicators. main() exercises the model without a BLE radio.
"""
from pathlib import Path
import json
import struct
import sys

HEADER = struct.Struct("<BBBBIIIHH")
OFFER = struct.Struct("<IBBI")
PRESENTATION = 1


def status_fragments(welcome, value_limit):
    """Split this example's complete WELCOME for the current notification limit."""
    capacity = value_limit - HEADER.size
    if capacity < 1:
        raise ValueError("Negotiate a larger ATT MTU before starting the session")
    version, kind, flags, reserved, epoch, obj, seq, _, size = HEADER.unpack_from(welcome)
    payload = welcome[HEADER.size:]
    for offset in range(0, len(payload), capacity):
        yield (HEADER.pack(version, kind, flags, reserved, epoch, obj, seq, offset, size)
               + payload[offset:offset + capacity])


class ActivityLight:
    def __init__(self, boot, board_id):
        if not 0 < boot <= 0xFFFFFFFF or len(board_id) != 8:
            raise ValueError("Supply a fresh boot nonce and a stable 8-byte board ID")
        self.boot = boot
        self.board_id = board_id
        self.disconnect()

    def identity(self):
        return struct.pack("<BBBBI8s", 1, 0x10, 1, 1, self.boot, self.board_id)

    def disconnect(self):
        self.epoch = self.context = self.features = self.revision = 0
        self.partial = None
        self.working = self.unread = False

    def receive(self, packet):
        """Return an optional WELCOME GATT value. Raise ValueError for bad input."""
        if len(packet) < HEADER.size:
            self.partial = None
            raise ValueError("truncated header")
        ver, kind, flags, rsv, epoch, obj, seq, offset, size = HEADER.unpack_from(packet)
        data = packet[HEADER.size:]
        if (ver != 1 or rsv or size > 1024 or offset + len(data) > size
                or (size and not data)):
            self.partial = None
            raise ValueError("invalid envelope")
        key = (kind, flags, epoch, obj, seq, size)
        if offset == 0:
            self.partial = (key, bytearray())
        if not self.partial or self.partial[0] != key or offset != len(self.partial[1]):
            self.partial = None
            raise ValueError("discontinuous fragment")
        assembled = self.partial[1]
        assembled.extend(data)
        if len(assembled) < size:
            return None
        self.partial = None
        if kind == 1:
            # This example exposes only Control and Status and supports new hosts.
            if flags or obj or seq or not epoch or len(assembled) != OFFER.size:
                raise ValueError("invalid HELLO")
            context, low, high, offered = OFFER.unpack(assembled)
            if not 0 < low <= 1 <= high:
                raise ValueError("incompatible contract")
            features = offered & PRESENTATION
            if self.epoch == epoch:
                if self.context != context or self.features != features:
                    raise ValueError("different binding on existing epoch")
            else:
                self.disconnect()
                self.context, self.epoch, self.features = context, epoch, features
            welcome = OFFER.pack(context, 1, 1, self.features)
            return HEADER.pack(1, 2, 0, 0, epoch, self.boot, 0, 0, len(welcome)) + welcome
        if not self.epoch or epoch != self.epoch:
            raise ValueError("stale epoch")
        if kind == 3 and self.features & PRESENTATION and obj == self.context:
            if flags or len(assembled) < 14 or assembled[9] > 3:
                raise ValueError("invalid snapshot")
            pos = 10
            bounds = [120, 320 if assembled[9] else 640] + [80] * assembled[9]
            for maximum in bounds:
                if pos + 2 > size:
                    raise ValueError("truncated text length")
                length = struct.unpack_from("<H", assembled, pos)[0]
                pos += 2
                if length > maximum or pos + length > size:
                    raise ValueError("invalid text length")
                if any(b != 10 and not 32 <= b <= 126 for b in assembled[pos:pos + length]):
                    raise ValueError("invalid text encoding")
                pos += length
            if pos != size:
                raise ValueError("trailing snapshot bytes")
            if self.revision and not 0 < (seq - self.revision) % (2**32) < 2**31:
                return None
            if seq:
                self.revision = seq
                self.working = bool(assembled[0] & 1)
                self.unread = bool(assembled[0] & 2)
        return None


def main():
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("vectors.json")
    vectors = json.loads(path.read_text())
    device = ActivityLight(0x11223344, bytes(range(1, 9)))
    assert device.identity().hex() == vectors["identity"]["activityLight"]
    fixtures = {case["name"]: case["packets"] for case in vectors["valid"]}
    hello = bytes.fromhex(fixtures["activity-light HELLO"][0])
    expected = bytes.fromhex(fixtures["activity-light WELCOME"][0])
    assert device.receive(hello) == expected
    assert list(status_fragments(expected, 61)) == [expected]
    tiny = list(status_fragments(expected, 24))
    assert [HEADER.unpack_from(fragment)[7] for fragment in tiny] == [0, 4, 8]
    assert b"".join(fragment[HEADER.size:] for fragment in tiny) == expected[HEADER.size:]
    snapshot = fixtures["working and unread SNAPSHOT in three fragments"]
    for packet in snapshot[:-1]:
        device.receive(bytes.fromhex(packet))
        assert not device.working and not device.unread
    device.receive(bytes.fromhex(snapshot[-1]))
    assert device.working and device.unread
    assert device.receive(hello) == expected and device.working
    changed_context = bytearray(hello)
    changed_context[20] ^= 1
    try:
        device.receive(changed_context)
    except ValueError:
        pass
    else:
        raise AssertionError("accepted a changed context without a fresh epoch")
    for case in vectors["malformed"]:
        device.disconnect()
        device.receive(hello)
        try:
            for packet in case["packets"]:
                device.receive(bytes.fromhex(packet))
        except ValueError:
            continue
        raise AssertionError(case["name"])
    print("Passed identity, negotiation, indicators and malformed-envelope checks.")


if __name__ == "__main__":
    main()
