"""Declarative Hardware Overlays (`pylotos.overlays`) & Sub-GHz `CC1101` Transceiver.

Demonstrates Phase 4W-2 runtime expansion-port hardware attachment:
- Inspecting & applying built-in overlays (`cardputer_adv_cap_lora1262`, `grove_nfc_ws1850s`, `grove_gnss_uart`)
- Runtime pin-guarded `hal.rf.attach("cc1101", ...)` for 433.92 / 868.35 MHz Sub-GHz FSK/OOK packets

Run locally:
    pylotos-sim examples/subghz_cc1101_and_overlays.py --board lilygo_t_embed --port 8080
"""

import hal
import pylotos.ui as ui
from pylotos import overlays

available = sorted(overlays.load_overlays().keys())
_rx_buf = bytearray(64)

st = ui.State(
    selected_overlay=available[0] if available else "cardputer_adv_cap_lora1262",
    active_driver="cc1101",
    freq_khz=868350,
    packets_tx=0,
    last_rx="(listening)",
)


def _attach_cc1101():
    hal.rf.attach("cc1101", port="ext_cap")
    hal.rf.set_region("EU868")
    hal.rf.set_freq(int(st.freq_khz) * 1000)
    st.active_driver = "cc1101"
    app.notify("Attached CC1101 @ {} kHz".format(st.freq_khz), level="ok", icon="wifi")


def _apply_selected_overlay():
    doc = overlays.apply_overlay(str(st.selected_overlay), persist=False)
    st.active_driver = str(doc.get("driver", "overlay"))
    app.notify("Applied " + str(st.selected_overlay), level="ok", icon="check")


def _tx_subghz_burst():
    hal.rf.set_freq(int(st.freq_khz) * 1000)
    hal.rf.send(b"PYLOT-SUBGHZ-PING")
    st.packets_tx = st.packets_tx + 1
    n = hal.rf.recv_into(_rx_buf)
    if n > 0:
        st.last_rx = bytes(_rx_buf[:n]).decode("utf-8", "replace")


app = ui.App(
    "Sub-GHz & Overlays",
    state=st,
    screens=[
        ui.Screen(
            "CC1101 RF",
            icon="wifi",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Freq", st.bind("freq_khz"), unit="kHz", accent="cyan"),
                        ui.Metric("Bursts", st.bind("packets_tx"), accent="gold"),
                    ],
                ),
                ui.Card(
                    "Sub-GHz Transceiver",
                    children=[
                        ui.KeyValue("Last RX", st.bind("last_rx")),
                        ui.Select("Channel kHz", st.bind("freq_khz"), options=[868100, 868350, 869525]),
                        ui.Button("Send Sub-GHz Burst", on_click=_tx_subghz_burst, shortcut="t"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "Overlays",
            icon="apps",
            children=[
                ui.KeyValue("Active Driver", st.bind("active_driver")),
                ui.Card(
                    "Pin-Guarded Expansion",
                    children=[
                        ui.Select("Overlay", st.bind("selected_overlay"), options=available),
                        ui.Button("Apply Overlay", on_click=_apply_selected_overlay, shortcut="o"),
                        ui.Button("Re-Attach CC1101", on_click=_attach_cc1101),
                    ],
                ),
            ],
        ),
    ],
)

_attach_cc1101()


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.rf.detach()
