"""MQTT 3.1.1 + Home Assistant Auto-Discovery Smart Home Node (`pylotos.mqtt_ha`).

Demonstrates Phase 4C zero-dependency Smart Home integration:
- Inspecting auto-generated `homeassistant/sensor/pylotos_<node>/*/config` discovery payloads
- Connecting & publishing retained discovery + live JSON state via `MqttHaService`

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

import json

import hal
import pylotos.ui as ui
from pylotos.mqtt_ha import MqttHaService, build_ha_discovery_messages

disc_msgs = build_ha_discovery_messages()

st = ui.State(
    broker="192.168.1.10",
    entities=len(disc_msgs),
    published=0,
    status="READY",
)


async def _sync_ha():
    svc = MqttHaService(host=str(st.broker), port=1883)
    try:
        await svc.connect()
        cnt = await svc.publish_discovery()
        mem = hal.mem_info()
        payload = json.dumps(
            {
                "heap_free": mem.get("heap_free_bytes", 0),
                "uptime_s": (st.published + 1) * 10,
                "battery_pct": hal.power_status().get("battery_pct", 100),
            }
        )
        await svc.publish("pylotos/" + svc.node_id + "/state", payload)
        await svc.close()
        st.entities = cnt
        st.published = st.published + 1
        st.status = "SYNCED"
        app.notify("Published {} HA entities + state".format(cnt), level="ok", icon="home")
    except Exception as exc:
        st.status = "OFFLINE"
        app.notify("Broker error: {}".format(exc), level="warn", icon="warn")


app = ui.App(
    "Home Assistant",
    state=st,
    screens=[
        ui.Screen(
            "MQTT Bridge",
            icon="home",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("HA Entities", st.bind("entities"), accent="cyan"),
                        ui.Metric("Publishes", st.bind("published"), accent="gold"),
                    ],
                ),
                ui.StatusBadge(
                    "Broker",
                    st.bind("status"),
                    tone=lambda: "ok" if st.status == "SYNCED" else "info",
                ),
                ui.Card(
                    "Auto-Discovery",
                    children=[
                        ui.TextField("MQTT Host", st.bind("broker")),
                        ui.Button("Publish Discovery & State", on_click=_sync_ha, shortcut="m"),
                    ],
                ),
            ],
        ),
    ],
)


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