"""NFC / RFID Badge & NDEF Scanner (`hal.nfc` + `pylotos.wireless`).

Ideal for the round `240x240` **M5Stack Dial** (onboard `WS1850S @ 0x28`) or any board
with a Grove RFID2 (`WS1850S`) / `PN532` / `MFRC522` expansion unit:
- Non-blocking ISO14443A tag UID polling (`hal.nfc.poll_tag_into`)
- Block 4 NTAG / MIFARE read + pure-Python NDEF URI/Text decoding (`decode_ndef_record`)
- Audible chime (`hal.beep`) on badge tap

Run locally:
    pylotos-sim examples/nfc_badge_scanner.py --board m5stack_dial --port 8080
"""

import sys

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

_uid_buf = bytearray(10)
_blk_buf = bytearray(16)

try:
    hal.nfc.open()
except OSError:
    hal.nfc.attach("ws1850s", port="grove_a", addr=0x28)

st = ui.State(
    scans=0,
    last_uid="(tap card)",
    ndef_val="(waiting)",
    access="READY",
)


def _format_hex(mv):
    return ":".join("{:02X}".format(b) for b in mv)


def _simulate_tap():
    # Convenient helper when previewing in `pylotos-sim` on desktop
    sim_mod = sys.modules.get("pylotos_sim.mock_hal")
    if sim_mod is not None:
        # Push a fresh simulated UID onto the mock NFC queue if available
        hal_nfc = getattr(hal, "nfc", None)
        if hal_nfc is not None:
            st.last_uid = "04:CA:FE:42"
            hal.nfc.read_block(4, _blk_buf)
            rec = wireless.decode_ndef_record(_blk_buf)
            st.ndef_val = str(rec.get("value", ""))
            st.scans = st.scans + 1
            st.access = "GRANTED"
            hal.beep(1320, 45, 50)
            app.notify("Simulated tag " + st.last_uid, level="ok", icon="check")


app = ui.App(
    "NFC Access",
    state=st,
    screens=[
        ui.Screen(
            "Scanner",
            icon="shield",
            children=[
                ui.Metric("Badges Read", st.bind("scans"), accent="gold"),
                ui.StatusBadge(
                    "Gate",
                    st.bind("access"),
                    tone=lambda: "ok" if st.access == "GRANTED" else "info",
                ),
                ui.Card(
                    "Last Tag",
                    children=[
                        ui.KeyValue("UID", st.bind("last_uid")),
                        ui.KeyValue("NDEF", st.bind("ndef_val")),
                        ui.Button("Simulate Card Tap", on_click=_simulate_tap, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(150)
def _poll_tag():
    ulen = hal.nfc.poll_tag_into(_uid_buf)
    if ulen <= 0:
        return
    uid_hex = _format_hex(memoryview(_uid_buf)[:ulen])
    st.last_uid = uid_hex
    st.scans = st.scans + 1
    st.access = "GRANTED"
    if hal.nfc.read_block(4, _blk_buf) > 0:
        try:
            rec = wireless.decode_ndef_record(_blk_buf)
            st.ndef_val = str(rec.get("value", rec.get("type", "raw")))
        except ValueError:
            st.ndef_val = "(raw block)"
    hal.beep(1320, 45, 50)
    app.notify("UID " + uid_hex, level="ok", icon="shield")


async def run(cv):
    try:
        await app.run_async(cv)
    finally:
        hal.nfc.sleep()
