"""ESP-NOW Zero-Copy Swarm Telemetry Radar (`hal.espnow`).

Demonstrates Phase 4W-1 connectionless 2.4 GHz peer-to-peer messaging across all
ESP32 / S3 / C3 / C6 boards without requiring an external Wi-Fi router:
- Broadcast + unicast peer registration (`hal.espnow.add_peer`)
- Zero-copy `hal.espnow.recv_into(buf, meta)` reception with RSSI history sparkline
- Authenticated frame sequence verification (`pylotos.wireless`)

Run locally:
    pylotos-sim examples/espnow_swarm_radar.py --board m5stack_nanoc6 --port 8080
    pylotos-sim examples/espnow_swarm_radar.py --board m5stack_atoms3 --port 8080
"""

import struct

import hal
import pylotos.ui as ui
from pylotos import wireless

BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
SWARM_KEY = b"pylotos-swarm-01"
_rx_buf = bytearray(250)
_rx_meta = {}

hal.espnow.open()
hal.espnow.add_peer(BROADCAST_MAC, 0)

st = ui.State(
    tx_count=0,
    rx_count=0,
    last_rssi=-40,
    peer_temp=23.5,
    rssi_hist=[-48, -45, -42, -40],
)


def _send_beacon():
    seq = st.tx_count + 1
    payload = struct.pack("<hH", int(st.peer_temp * 10), 88)
    pkt = wireless.pack_frame(SWARM_KEY, seq, payload)
    hal.espnow.send(BROADCAST_MAC, pkt)
    st.tx_count = seq


app = ui.App(
    "ESP-NOW Radar",
    state=st,
    screens=[
        ui.Screen(
            "Swarm",
            icon="wifi",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Peers RX", st.bind("rx_count"), accent="cyan"),
                        ui.Metric("RSSI", st.bind("last_rssi"), unit="dBm", accent="gold"),
                    ],
                ),
                ui.Sparkline("Link RSSI", st.bind("rssi_hist"), unit="dBm", accent="cyan"),
                ui.Card(
                    "Beacon Control",
                    children=[
                        ui.Slider("Sim Temp", st.bind("peer_temp"), min=15.0, max=40.0, step=0.5, unit="C"),
                        ui.Button("Broadcast Beacon", on_click=_send_beacon, shortcut="b"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(200)
def _poll_espnow():
    n = hal.espnow.recv_into(_rx_buf, _rx_meta)
    if n <= 0:
        return
    try:
        _seq, body = wireless.unpack_frame(SWARM_KEY, memoryview(_rx_buf)[:n])
        if len(body) >= 4:
            t_d10, _batt = struct.unpack("<hH", body[:4])
            st.peer_temp = round(t_d10 / 10.0, 1)
        rssi = int(_rx_meta.get("rssi", -40))
        st.last_rssi = rssi
        st.rx_count = st.rx_count + 1
        hist = list(st.rssi_hist)
        hist.append(rssi)
        st.rssi_hist = hist[-16:]
    except ValueError:
        pass


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.espnow.close()
