"""ESP-NOW / WebSocket framing (MicroPython). See docs/espnow-binary-protocol.md."""

WIRE_MAGIC = 0x4C
MSG_BRIDGE_CH = 0x10
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
WS_FLAG_BROADCAST = 0x01
MAX_PEERS = 20


def parse_ws_downlink(frame):
    """Return (peer_bytes, espnow_packet, is_broadcast)."""
    if not frame or len(frame) < 8:
        raise ValueError("frame too short")
    flags = frame[0]
    peer = frame[1:7]
    pkt = frame[7:]
    broadcast = bool(flags & WS_FLAG_BROADCAST) or peer == BROADCAST_MAC
    return peer, pkt, broadcast


def pack_ws_uplink(peer, espnow_packet):
    return bytes([0]) + peer + espnow_packet


def parse_bridge_channel(pkt):
    if len(pkt) >= 3 and pkt[0] == WIRE_MAGIC and pkt[1] == MSG_BRIDGE_CH:
        return pkt[2]
    return None
