import json
import time
import ubinascii
import network


def _sta_mac_hex():
    """Read STA MAC without leaving the radio up (wifi_ap owns bring-up)."""
    sta = network.WLAN(network.STA_IF)
    was_on = False
    try:
        was_on = sta.active()
    except Exception:
        pass
    if not was_on:
        try:
            sta.active(True)
            time.sleep_ms(50)
        except Exception:
            pass
    try:
        mac = ubinascii.hexlify(sta.config("mac")).decode().lower()
    except Exception:
        mac = "000000000000"
    if not was_on:
        try:
            sta.active(False)
        except Exception:
            pass
    return mac


class Settings(dict):
    SETTINGS_FILE = "/settings.json"

    def __init__(self):
        super().__init__()
        self.load()

    def set_defaults(self):
        mac = _sta_mac_hex()
        self["name"] = "bridge-" + mac
        self["wifi_channel"] = 6
        self["ap_password"] = ""
        self["ap_ip"] = "192.168.4.1"
        self["ws_port"] = 80
        self["max_peers"] = 20

    def save(self):
        try:
            with open(self.SETTINGS_FILE, "w") as file:
                file.write(json.dumps(self))
        except Exception as e:
            print("Error saving settings:", e)

    def load(self):
        try:
            with open(self.SETTINGS_FILE, "r") as file:
                loaded = json.load(file)
            if not isinstance(loaded, dict):
                raise ValueError("settings.json is not an object")
        except Exception:
            print("Error loading settings")
            self.clear()
            self.set_defaults()
            self.save()
            return
        self.clear()
        self.set_defaults()
        for k, v in loaded.items():
            self[k] = v

  