import pytest
import time
from helpers.container import send_sighup
from helpers.config import config_read, config_set, config_commit, config_get
from helpers.ubus import get_test_bands, verify_ubus_ssid

MAP_GW = "map-gw"
PEER_CONTAINERS = ["map-ext1", "map-ext2"]
MAPCONTROLLER_CONFIG = "mapcontroller"
WIRELESS_CONFIG = "wireless"

NEW_SSID = "MAP-Test-AP-Custom"
NEW_ENCRYPTION = "sae"
NEW_KEY = "newpassword"


def config_set_ap(container, ssid, encryption, key, type="fronthaul"):
    """
    Update 'ap' sections matching 'type' in mapcontroller config.
    """
    uci_dict = config_read(container, MAPCONTROLLER_CONFIG)

    for section in uci_dict:
        if section.startswith("@ap") or section.startswith("ap"):
            section_type = uci_dict[section].get("type", "")
            if section_type == type:
                config_set(container, MAPCONTROLLER_CONFIG, section, "ssid", ssid)
                config_set(container, MAPCONTROLLER_CONFIG, section, "encryption", encryption)
                config_set(container, MAPCONTROLLER_CONFIG, section, "key", key)

    config_commit(container, MAPCONTROLLER_CONFIG)


@pytest.mark.parametrize("container", [MAP_GW] + PEER_CONTAINERS)
def test_multiap_set_fronthaul(container):
    config_set_ap(MAP_GW, NEW_SSID, encryption=NEW_ENCRYPTION, key=NEW_KEY)

    result = send_sighup(MAP_GW, "mapcontroller")
    assert result.returncode == 0, f"Failed to SIGHUP mapcontroller: {result.stderr}"

    # Wait for AP auto-configuration
    time.sleep(10)

    # (Optional) SIGHUP wifimngr to reload with changed wireless config
    for c in [MAP_GW] + PEER_CONTAINERS:
        result = send_sighup(c, "wifimngr")
        assert result.returncode == 0, f"Failed to SIGHUP wifimngr on {c}: {result.stderr}"

    # Verify wireless wifi-iface sections having multiap=2 are correctly updated
    for c in [MAP_GW] + PEER_CONTAINERS:
        wifi_dict = config_read(c, WIRELESS_CONFIG)
        for section in wifi_dict:
            if section.startswith("@wifi-iface") or section.startswith("wifi-iface"):
                multiap_val = wifi_dict[section].get("multiap", None)
                if multiap_val == "2":
                    ssid_val = wifi_dict[section].get("ssid", None)
                    encryption_val = wifi_dict[section].get("encryption", None)
                    key_val = wifi_dict[section].get("key", None)

                    assert ssid_val == NEW_SSID, (
                        f"{c} section {section} has multiap={multiap_val} but SSID='{ssid_val}', "
                        f"expected '{NEW_SSID}'"
                    )
                    assert encryption_val == NEW_ENCRYPTION, (
                        f"{c} section {section} has multiap={multiap_val} but encryption='{encryption_val}', "
                        f"expected '{NEW_ENCRYPTION}'"
                    )
                    assert key_val == NEW_KEY, (
                        f"{c} section {section} has multiap={multiap_val} but key='{key_val}', "
                        f"expected '{NEW_KEY}'"
                    )

    # FIXME: wifi=TEST returns fixed values now. So, cannot verify ubus output
    #for c in [MAP_GW] + PEER_CONTAINERS:
    #    verify_ubus_ap_status(c, NEW_SSID, NEW_ENCRYPTION, NEW_KEY)

