import json
from .config import config_read
from .container import exec_in_container

MULTIAP_MAP = {
    "fronthaul": "2",
    "backhaul": "1",
    "none": None,     # no 'multiap' option
}

#TODO: move to config.py
def get_test_bands(container):
    """
    Reads wireless config wifi-device sections and returns a list of
    valid bands present in this container. (2g, 5g, 6g)
    """
    wireless = config_read(container, "wireless")

    bands = []
    for section, opts in wireless.items():
        if section.startswith("wifi-device"):
            band = opts.get("band")
            if band in ("2g", "5g", "6g"):
                bands.append(band)

    return bands


def ubus_get_ap_status(container, ifname):
    """
    Call: ubus call wifi.ap.<ifname> status
    Return parsed JSON or raise error.
    """
    cmd = ["ubus", "call", f"wifi.ap.{ifname}", "status"]
    result = exec_in_container(container, cmd)

    if result.returncode != 0:
        raise RuntimeError(
            f"[{container}] Failed ubus call for ifname={ifname}: {result.stderr}"
        )

    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError:
        raise RuntimeError(
            f"[{container}] UBUS returned invalid JSON for ifname={ifname}: {result.stdout}"
        )


def verify_ubus_ssid(container, expected_ssid, type="fronthaul"):
    """
    Verifies SSID via ubus for all wifi-iface sections matching multiap type.

    type = "fronthaul" -> multiap == "2"
    type = "backhaul"  -> multiap == "1"
    type = "none"      -> multiap option not present
    """
    desired_multiap = MULTIAP_MAP[type]
    wifi_cfg = config_read(container, "wireless")

    found = False

    for section, opts in wifi_cfg.items():
        if not (section.startswith("@wifi-iface") or section.startswith("wifi-iface")):
            continue

        multiap_val = opts.get("multiap", None)

        # Match filter
        if desired_multiap is None:
            if "multiap" in opts:
                continue
        else:
            if multiap_val != desired_multiap:
                continue

        ifname = opts.get("ifname")
        if not ifname:
            raise RuntimeError(f"{container} section {section} missing 'ifname'")

        found = True
        status = ubus_get_ap_status(container, ifname)

        ubus_ssid = status.get("ssid") or status.get("config", {}).get("ssid")

        assert (
            ubus_ssid == expected_ssid
        ), (
            f"{container}: ubus ssid mismatch for iface {ifname} (section {section}). "
            f"Expected='{expected_ssid}', got='{ubus_ssid}', ubus status={status}"
        )

    assert found, f"No wifi-iface sections in {container} matching type '{type}'"

