"""Power Management (`esp_pm`), Tickless Light Sleep & ULP Coprocessor Monitor.

Demonstrates Phase 2B & Phase 4B ultra-low-power features:
- Dynamic Frequency Scaling (DFS) & Automatic Tickless Light Sleep (`hal.pm_configure`)
- Smooth backlight dimming (`hal.display_backlight`) & PMIC battery telemetry (`hal.power_status`)
- ULP-RISC-V (ESP32-S3) / LP-Core (ESP32-C6) shared RTC memory (`hal.ulp_*`)

Run locally:
    pylotos-sim examples/power_sleep_and_ulp_monitor.py --board m5stack_stickc_plus2 --port 8080
"""

import hal
import pylotos.ui as ui

pwr = hal.power_status()
ulp = hal.ulp_info()
hal.ulp_write_shared(0, 420)  # Wake threshold in RTC slow RAM

st = ui.State(
    batt_pct=int(pwr.get("battery_pct", 100)),
    batt_mv=int(pwr.get("battery_mv", 4100)),
    max_mhz=240,
    min_mhz=80,
    tickless=True,
    backlight=80,
    ulp_arch=str(ulp.get("arch", "none")),
    ulp_thresh=hal.ulp_read_shared(0),
)


def _apply_pm():
    hal.pm_configure(int(st.max_mhz), int(st.min_mhz), bool(st.tickless))
    hal.display_backlight(int(st.backlight))
    hal.ulp_write_shared(0, int(st.ulp_thresh))
    app.notify(
        "PM {}-{} MHz, sleep={}".format(st.min_mhz, st.max_mhz, st.tickless),
        level="ok",
        icon="battery",
    )


def _nap_test():
    slept = hal.light_sleep(50)
    app.toast("Woke after {} ms light sleep".format(slept))


app = ui.App(
    "Power & ULP",
    state=st,
    screens=[
        ui.Screen(
            "esp_pm & Battery",
            icon="battery",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Battery", st.bind("batt_pct"), unit="%", accent="gold"),
                        ui.Metric("Voltage", st.bind("batt_mv"), unit="mV", accent="cyan"),
                    ],
                ),
                ui.Card(
                    "Tickless Governor",
                    children=[
                        ui.Switch("Auto Light Sleep", st.bind("tickless")),
                        ui.Select("Max CPU MHz", st.bind("max_mhz"), options=[80, 160, 240]),
                        ui.Slider("Backlight", st.bind("backlight"), min=10, max=100, step=10, unit="%"),
                        ui.Button("Apply Governor", on_click=_apply_pm, shortcut="a"),
                        ui.Button("50 ms Light Sleep Nap", on_click=_nap_test, shortcut="n"),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "ULP RTC RAM",
            icon="cpu",
            children=[
                ui.KeyValue("Coprocessor", st.bind("ulp_arch")),
                ui.Card(
                    "Shared Wake Threshold",
                    children=[
                        ui.NumberField("RTC Reg[0]", st.bind("ulp_thresh"), min=100, max=2000, step=20),
                        ui.Button("Sync to ULP", on_click=_apply_pm, shortcut="u"),
                    ],
                ),
            ],
        ),
    ],
)


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