"""3-Layer Per-Device `app_config`, Runtime `policy` Gate & VFS Quota Demo.

Demonstrates Phase 2A & Phase 3B security and fleet configuration APIs:
- Loading & saving per-device overrides via `pylotos.app_config`
- Testing `pylotos.policy.evaluate()` (`ALLOW` vs `ASK` vs non-overridable `DENY` on secrets)
- Checking LittleFS `/apps` storage quota via `pylotos.app_store.check_quota()`

Run locally:
    pylotos-sim examples/app_config_and_policy_demo.py --board m5stack_core2 --port 8080
"""

import pylotos.ui as ui
from pylotos import app_config, app_store, policy

cfg = app_config.load(
    defaults={"node_label": "Lab-Node-01", "quota_kb": 512},
    app_name="fleet_node",
)
quota = app_store.check_quota(extra_bytes=4096, quota_kb=int(cfg.get("quota_kb", 512)))

st = ui.State(
    node_label=str(cfg.get("node_label", "Lab-Node-01")),
    quota_kb=int(cfg.get("quota_kb", 512)),
    used_kb=int(quota.get("used_bytes", 0)) // 1024,
    last_decision="ALLOW (ready)",
)


def _save_cfg():
    app_config.save(
        {"node_label": st.node_label, "quota_kb": int(st.quota_kb)},
        app_name="fleet_node",
    )
    app.notify("Saved /apps/.config/fleet_node.json", level="ok", icon="check")


def _probe_policy(action, target):
    dec, reason = policy.evaluate(action, target=target, source="lan")
    st.last_decision = "{}: {}".format(dec.upper(), reason)
    lvl = "err" if dec == policy.DENY else ("warn" if dec == policy.ASK else "ok")
    app.notify("{} -> {}".format(action, dec.upper()), level=lvl, icon="lock")


app = ui.App(
    "Policy & Config",
    state=st,
    screens=[
        ui.Screen(
            "Policy Gate",
            icon="lock",
            children=[
                ui.StatusBadge(
                    "Decision",
                    st.bind("last_decision"),
                    tone=lambda: "err" if st.last_decision.startswith("DENY") else "info",
                ),
                ui.Card(
                    "Simulate LAN / MCP Request",
                    children=[
                        ui.Button(
                            "Test ALLOW (board.describe)",
                            on_click=lambda: _probe_policy("board.describe", None),
                            shortcut="1",
                        ),
                        ui.Button(
                            "Test ASK (apps.write)",
                            on_click=lambda: _probe_policy("apps.write", "demo.py"),
                            shortcut="2",
                        ),
                        ui.Button(
                            "Test DENY (nvs.get wifi_pass)",
                            on_click=lambda: _probe_policy("nvs.get", "wifi_pass"),
                            shortcut="3",
                        ),
                    ],
                ),
            ],
        ),
        ui.Screen(
            "App Config",
            icon="settings",
            children=[
                ui.Grid(
                    cols=2,
                    children=[
                        ui.Metric("Used VFS", st.bind("used_kb"), unit="KB", accent="cyan"),
                        ui.Metric("Quota", st.bind("quota_kb"), unit="KB", accent="gold"),
                    ],
                ),
                ui.Card(
                    "Per-Device Override",
                    children=[
                        ui.TextField("Node Label", st.bind("node_label")),
                        ui.Slider("Quota KB", st.bind("quota_kb"), min=128, max=2048, step=128, unit="KB"),
                        ui.Button("Save Device Config", on_click=_save_cfg, shortcut="s"),
                    ],
                ),
            ],
        ),
    ],
)


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