"""ESP32-C6 Wi-Fi 6 `iTWT`, NimBLE 5.3 Coded PHY & `IEEE 802.15.4` Node.

Demonstrates the triple-radio 2.4 GHz `esp_coex` capabilities on ESP32-C6 boards
(`m5stack_nanoc6`, `waveshare_esp32c6_lcd_147`, `seeed_xiao_esp32c6`):
- `hal.net.twt()` Individual Target Wake Time (`802.11ax`) & `hal.net.coex()` arbiter
- `hal.ble.coded_phy()` Long-Range S=8 BLE 5.3 advertising/link configuration
- `hal.ieee802154` raw `802.15.4` MAC frame TX (`--wireless-profile 802154`)

Run locally:
    pylotos-sim examples/c6_wifi6_twt_and_802154.py --board waveshare_esp32c6_lcd_147 --port 8080
"""

import struct

import hal
import pylotos.ui as ui

st = ui.State(
    coex_mode="balance",
    twt_on=True,
    twt_wake_ms=2000,
    coded_s8=True,
    zig_ch=15,
    frames_tx=0,
)

hal.ieee802154.open(15, 0x1234, 0x0001)


def _apply_radio_cfg():
    hal.net.coex(str(st.coex_mode))
    hal.net.twt(bool(st.twt_on), int(st.twt_wake_ms), 12)
    hal.ble.coded_phy(bool(st.coded_s8), True)
    app.notify("Synced Wi-Fi 6 iTWT + BLE Coded PHY", level="ok", icon="wifi")


def _send_802154():
    seq = (st.frames_tx + 1) & 0xFF
    # Minimal IEEE 802.15.4 data frame header + sensor payload
    hdr = struct.pack("<HBHHH", 0x8861, seq, 0x1234, 0xFFFF, 0x0001)
    hal.ieee802154.open(int(st.zig_ch), 0x1234, 0x0001)
    hal.ieee802154.send(hdr + b"pylot-c6")
    st.frames_tx = st.frames_tx + 1
    app.toast("802.15.4 Ch{} TX #{}".format(st.zig_ch, st.frames_tx))


app = ui.App(
    "C6 Triple-Radio",
    state=st,
    screens=[
        ui.Screen(
            "Wi-Fi 6 & BLE",
            icon="wifi",
            children=[
                ui.Card(
                    "2.4 GHz Coex & iTWT",
                    children=[
                        ui.Select("Coex Priority", st.bind("coex_mode"), options=["balance", "wifi", "ble"]),
                        ui.Switch("Wi-Fi 6 iTWT", st.bind("twt_on")),
                        ui.Slider("Wake Interval", st.bind("twt_wake_ms"), min=500, max=5000, step=500, unit="ms"),
                        ui.Switch("BLE Coded PHY (S=8)", st.bind("coded_s8")),
                        ui.Button("Apply Radio Policy", on_click=_apply_radio_cfg, shortcut="a"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "802.15.4 MAC",
            icon="ble",
            children=[
                ui.Metric("PAN 0x1234 TX", st.bind("frames_tx"), accent="gold"),
                ui.Card(
                    "IEEE 802.15.4 Raw",
                    children=[
                        ui.Select("Channel", st.bind("zig_ch"), options=[11, 15, 20, 25, 26]),
                        ui.Button("Broadcast 802.15.4 Frame", on_click=_send_802154, shortcut="z"),
                    ],
                ),
            ],
        ),
    ],
)


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