"""OS PubSub EventBus, Background Services & Asymmetric OTA Monitor.

Demonstrates Phase 1 & Phase 3B OS integration:
- Subscribing to typed `pylotos.events` topics (`wifi.changed`, `power.battery`, custom topics)
- Inspecting declarative background services (`pylotos.services`)
- Reading live Asymmetric Recovery-OTA health (`sys_ota.status()`) & heap headroom (`hal.mem_info()`)

Run locally:
    pylotos-sim examples/pubsub_service_monitor.py --board m5stack_cardputer_adv --port 8080
"""

import hal
import pylotos.ui as ui
import sys_ota
from pylotos.events import TOPIC_POWER_BATTERY, TOPIC_WIFI_CHANGED, events
from pylotos.services import services

st = ui.State(
    heap_kb=0,
    batt_pct=100,
    wifi_ip="0.0.0.0",
    ota_schema="asym-v1",
    svc_running=0,
    events_rx=0,
    last_event="ready",
)


def _refresh_telemetry():
    mem = hal.mem_info()
    st.heap_kb = int(mem.get("heap_free_bytes", 0)) // 1024
    ota = sys_ota.status()
    st.ota_schema = str(ota.get("ota_schema", "asym-v1"))
    svc_stat = services.status()
    st.svc_running = int(svc_stat.get("running", 0))
    wifi = events.last(TOPIC_WIFI_CHANGED, {}) or {}
    if isinstance(wifi, dict) and wifi.get("ip"):
        st.wifi_ip = str(wifi["ip"])
    pwr = events.last(TOPIC_POWER_BATTERY, {}) or {}
    if isinstance(pwr, dict) and "battery_pct" in pwr:
        st.batt_pct = int(pwr["battery_pct"])


def _on_bus_event(topic, payload):
    st.events_rx = st.events_rx + 1
    st.last_event = "{}: {}".format(topic, payload)
    _refresh_telemetry()


events.subscribe("app.ping", _on_bus_event)
events.subscribe(TOPIC_WIFI_CHANGED, _on_bus_event)
events.subscribe(TOPIC_POWER_BATTERY, _on_bus_event)
_refresh_telemetry()


def _emit_ping():
    n = st.events_rx + 1
    events.publish("app.ping", {"seq": n})
    app.notify("Published app.ping #{}".format(n), level="ok", icon="bolt")


app = ui.App(
    "OS Monitor",
    state=st,
    screens=[
        ui.Screen(
            "System",
            icon="cpu",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Free Heap", st.bind("heap_kb"), unit="KB", accent="cyan"),
                        ui.Metric("Battery", st.bind("batt_pct"), unit="%", accent="gold"),
                    ],
                ),
                ui.Card(
                    "OS & OTA State",
                    children=[
                        ui.KeyValue("OTA Schema", st.bind("ota_schema")),
                        ui.KeyValue("Wi-Fi IP", st.bind("wifi_ip")),
                        ui.KeyValue("Active Services", st.bind("svc_running")),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "EventBus",
            icon="apps",
            children=[
                ui.StatusBadge(
                    "PubSub",
                    lambda: "{} events".format(st.events_rx),
                    tone="ok",
                ),
                ui.Card(
                    "Live Bus",
                    children=[
                        ui.KeyValue("Last Event", st.bind("last_event")),
                        ui.Button("Publish app.ping", on_click=_emit_ping, shortcut="p"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _poll_sys():
    _refresh_telemetry()


async def run(cv):
    await app.run_async(cv)
