import json
import network
import time


def xor_encrypt_decrypt(input_string, key):
    output = "".join(chr(ord(char) ^ key) for char in input_string)
    return output


def wifi_connect(ssid, password, timeout=10):
    """
    Connects to the specified Wi-Fi access point.

    :param ssid: The SSID of the Wi-Fi network.
    :param password: The password for the Wi-Fi network.
    :param timeout: Time in seconds to wait for connection.
    :return: True if connected, False otherwise.
    """
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    if not wlan.isconnected():
        print(f"Connecting to network: {ssid}...")
        wlan.connect(ssid, password)

        start_time = time.time()
        while not wlan.isconnected():
            if time.time() - start_time > timeout:
                print("Connection timeout!")
                wlan.active(False)
                del wlan
                return False
            time.sleep(1)

    print("Network connected!")
    print("IP Address:", wlan.ifconfig()[0])
    return True


def wifi_setup():
    # try:
    #     with open("config.json", "r") as f:
    #         config = json.load(f)

    #     for ap in config.get("access_points", []):
    #         result = wifi_connect(
    #             ap["ssid"], xor_encrypt_decrypt(ap["secret"], config["xor_key"])
    #         )
    #         if result:
    #             return

    # except (OSError, ValueError) as e:
    #     print("OSError config.json unreadable or no")

    print("Falling back on selfhosted AP")
    ap = network.WLAN(network.AP_IF)
    ap.config(essid="RP2040-AP", password="openwater")
    ap.ifconfig(("192.168.4.1", "255.255.255.0", "192.168.4.1", "192.168.4.1"))
    ap.active(True)
    print("SSID RP2040-AP")
    return


print("Attempting to connect to wifi")
# time.sleep(10)
wifi_setup()
