def parse_mac(value):
    raw = value.strip().lower().replace(":", "").replace("-", "")
    if len(raw) != 12:
        raise ValueError("address must be 12 hex chars or aa:bb:cc:dd:ee:ff")
    try:
        return bytes.fromhex(raw)
    except ValueError:
        raise ValueError("address contains non-hex characters")


def format_mac(mac_bytes):
    return ":".join("{:02x}".format(b) for b in mac_bytes)


def print_bridge_ip(ws_port=80):
    import network

    try:
        port = int(ws_port)
    except (TypeError, ValueError):
        port = 80

    ips = []
    try:
        sta = network.WLAN(network.STA_IF)
        if sta.active():
            ip = sta.ifconfig()[0]
            if ip and ip != "0.0.0.0":
                ips.append(("STA", ip))
    except Exception:
        pass
    try:
        ap = network.WLAN(network.AP_IF)
        if ap.active():
            ip = ap.ifconfig()[0]
            if ip and ip != "0.0.0.0":
                ips.append(("AP", ip))
    except Exception:
        pass

    if not ips:
        print("bridge IP: (AP not up)")
        return

    # Prefer AP address — Pi joins the bridge access point.
    ips.sort(key=lambda x: 0 if x[0] == "AP" else 1)
    label, ip = ips[0]
    print("bridge IP (%s):" % label, ip)
    print("bridge_ws_url: ws://%s:%s/ws" % (ip, port))
