"""Declarative Background Service + Live Telemetry Dashboard (`SERVICE_MANIFEST`).

Can be installed in TWO ways on PylotOS:
1. Copy to `/apps/services/background_env_service.py` -> runs headless in the background
   via `SERVICE_MANIFEST` and `run_service(stop_event)`, publishing `sensor.env` onto `pylotos.events`!
2. Run directly as a foreground app or in `pylotos-sim`:
       pylotos-sim examples/background_env_service.py --board m5stack_atoms3 --port 8080
"""

import asyncio

import pylotos.ui as ui
from pylotos.events import events

SERVICE_MANIFEST = {
    "name": "env_sampler",
    "version": "1.0.0",
    "autostart": True,
    "caps": ["i2c"],
    "restart_on_crash": True,
}

st = ui.State(co2_ppm=440, lux=320, samples=0)


def _sample_once():
    st.co2_ppm = 420 + ((st.co2_ppm + 19) % 480)
    st.lux = 150 + ((st.lux + 45) % 650)
    st.samples = st.samples + 1
    events.publish("sensor.env", {"co2_ppm": st.co2_ppm, "lux": st.lux, "seq": st.samples})


async def run_service(stop_event):
    """Entry point invoked automatically by `pylotos.services` when placed in `/apps/services/`."""
    while not stop_event.is_set():
        _sample_once()
        await asyncio.sleep(2)


app = ui.App(
    "Env Service",
    state=st,
    screens=[
        ui.Screen(
            "Daemon",
            icon="chart",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("CO2", st.bind("co2_ppm"), unit="ppm", accent="cyan"),
                        ui.Metric("Light", st.bind("lux"), unit="lx", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Service Publisher",
                    children=[
                        ui.KeyValue("Samples Emitted", st.bind("samples")),
                        ui.Button("Sample & Publish Now", on_click=_sample_once, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


@app.every(2000)
def _tick():
    _sample_once()


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