"""Bridge Wi-Fi: AP for Pi WebSocket client, STA for ESP-NOW (ESP32-C3: AP first)."""

import time

import network


def _wait_active(wlan, timeout_ms=1000):
    for _ in range(timeout_ms // 20):
        if wlan.active():
            return True
        time.sleep_ms(20)
    return bool(wlan.active())


def _boot_channel(settings):
    try:
        return max(1, min(11, int(settings.get("wifi_channel", 6))))
    except (TypeError, ValueError):
        return 6


def init_bridge_network(settings):
    """Bring up AP (Pi) then STA (ESP-NOW). Channel set on AP at boot only."""
    ch = _boot_channel(settings)
    sta = network.WLAN(network.STA_IF)
    ap = network.WLAN(network.AP_IF)

    try:
        sta.active(False)
        ap.active(False)
    except Exception:
        pass
    time.sleep_ms(100)

    essid = settings.get("name") or "espnow-bridge"
    password = settings.get("ap_password") or ""

    ap.active(True)
    if not _wait_active(ap):
        raise RuntimeError("AP did not become active")

    if password:
        ap.config(essid=essid, password=password, channel=ch)
    else:
        ap.config(essid=essid, channel=ch)

    ap_ip = settings.get("ap_ip") or "192.168.4.1"
    try:
        ap.ifconfig((ap_ip, "255.255.255.0", ap_ip, "8.8.8.8"))
    except Exception as e:
        print("ap ifconfig:", e)

    sta.active(True)
    if not _wait_active(sta):
        raise RuntimeError("STA did not become active")
    try:
        sta.config(pm=network.WLAN.PM_NONE)
    except Exception:
        pass

    try:
        actual = ap.config("channel")
    except Exception:
        actual = ch
    print("bridge AP:", essid, "channel=", actual, "ip=", ap.ifconfig()[0])
