"""Wired Network Failover & USB-NCM Console — PylotOS Wired C HAL (`hal.net`).

Demonstrates:
- OS-owned `hal.net` multi-interface routing (`eth_spi` W5500 -> `usb_ncm` -> `wifi_sta`)
- Deterministic hot-plug failover and manual route priority tuning
- Restricting the `:8266` AI Bridge / OTA server to wired interfaces (`set_bridge_ifaces`)
- Static IPv4 assignment without breaking Wi-Fi fallback

Run locally:
    pylotos-sim examples/ethernet_failover_and_usb_ncm.py --board m5stack_cores3
"""

import hal
import pylotos.ui as ui

st = ui.State(
    route="wifi_sta",
    eth_ip="0.0.0.0",
    ncm_ip="0.0.0.0",
    wifi_ip="192.168.1.42",
    bridge_mode="All (Eth + Wi-Fi)",
    failovers=0,
    status="Ready — Wi-Fi STA active",
)


def _refresh():
    ifaces = hal.net.interfaces()
    desc = hal.describe().get("wired", {})
    st.route = hal.net.active_route()
    st.eth_ip = ifaces.get("eth_spi", {}).get("ip", "0.0.0.0")
    st.ncm_ip = ifaces.get("usb_ncm", {}).get("ip", "0.0.0.0")
    st.wifi_ip = ifaces.get("wifi_sta", {}).get("ip", "0.0.0.0")
    st.failovers = int(desc.get("failover_count", 0))


def attach_w5500():
    try:
        hal.net.attach_eth("w5500", port="mbus", spi_host=1, cs=5, irq=35, rst=33, dhcp=True)
        _refresh()
        st.status = "W5500 Ethernet UP -> primary route"
        app.notify("Ethernet UP: %s" % st.eth_ip, level="ok")
    except OSError as exc:
        st.status = "W5500 attach failed: %s" % exc
        app.notify("W5500 unavailable on board", level="warn")


def detach_w5500():
    hal.net.detach_eth()
    _refresh()
    st.status = "Ethernet unplugged -> failover to %s" % st.route
    app.notify("Failover -> %s" % st.route, level="warn")


def enable_usb_ncm():
    try:
        hal.net.attach_usb_ncm()
        _refresh()
        st.status = "USB-NCM NIC UP (%s)" % st.ncm_ip
        app.notify("USB-NCM active: %s" % st.ncm_ip, level="ok")
    except OSError:
        st.status = "USB-NCM requires ESP32-S3 USB-OTG"
        app.notify("USB-NCM requires ESP32-S3", level="warn")


def lock_bridge_wired_only():
    hal.net.set_bridge_ifaces(["eth_spi", "eth_rmii", "usb_ncm"])
    st.bridge_mode = "Wired Only (Zero Wi-Fi Bridge)"
    st.status = "Bridge :8266 locked to wired NICs"
    app.notify("Bridge restricted to wired NICs", level="info")


def assign_static_eth():
    hal.net.set_static_ip("eth_spi", "10.20.30.40", "255.255.255.0", "10.20.30.1")
    _refresh()
    st.status = "Static IP applied on eth_spi"
    app.notify("Static IP: 10.20.30.40", level="ok")


route_screen = ui.Screen(
    "Wired Routing",
    [
        ui.Grid(
            [
                ui.Metric("Active Route", st.bind("route"), accent="cyan"),
                ui.Metric("Failovers", st.bind("failovers"), accent="gold"),
            ],
            cols=2,
        ),
        ui.Card(
            "Interface Table (HAL_OWNER_OS)",
            [
                ui.KeyValue("W5500 SPI Eth", st.bind("eth_ip")),
                ui.KeyValue("USB-NCM (S3)", st.bind("ncm_ip")),
                ui.KeyValue("Wi-Fi STA", st.bind("wifi_ip")),
                ui.KeyValue("Bridge Policy", st.bind("bridge_mode")),
            ],
        ),
        ui.Row(
            [
                ui.Button("Attach W5500", attach_w5500, shortcut="1"),
                ui.Button("Unplug Eth", detach_w5500, shortcut="2"),
            ]
        ),
        ui.Row(
            [
                ui.Button("USB-NCM", enable_usb_ncm, shortcut="3"),
                ui.Button("Lock Bridge", lock_bridge_wired_only, shortcut="4"),
            ]
        ),
        ui.Button("Set Static Eth IP (10.20.30.40)", assign_static_eth, shortcut="5"),
        ui.StatusBadge("Status", st.bind("status"), tone="ok"),
    ],
)

app = ui.App("Wired Net Failover", [route_screen], state=st)
_refresh()


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