# tiny_config — persistent device config at /flash/tiny.json ({{slug}}).
# Keys: device_id, token (tind_…), name, api, networks [{ssid,key},…]. `tiny-tech flash` calls
# merge(load_raw() or {}, payload) then save(cfg) — keep these two signatures stable.
import json
PATH = "/flash/tiny.json"
DEFAULT_API = "https://tiny.technology"
SCALAR_KEYS = ("device_id", "token", "api", "name")


def load_raw():
    try:
        with open(PATH) as f:
            return json.load(f)
    except (OSError, ValueError):
        return None


def networks(cfg):
    nets = [n for n in (cfg or {}).get("networks", []) if n.get("ssid")]
    return nets


def complete(cfg):
    return bool(cfg and cfg.get("device_id") and cfg.get("token") and networks(cfg))


def merge(cfg, sent):
    """Fold a provisioning payload into cfg (mutates + returns). A non-empty `networks` REPLACES the list;
    a single ssid/key upserts to the FRONT (the network you are standing next to)."""
    for k in SCALAR_KEYS:
        if sent.get(k):
            cfg[k] = str(sent[k])
    if sent.get("networks"):
        cfg["networks"] = [{"ssid": n["ssid"], "key": n.get("key", "")} for n in sent["networks"] if n.get("ssid")]
    elif sent.get("ssid"):
        nets = [n for n in cfg.get("networks", []) if n.get("ssid") != sent["ssid"]]
        cfg["networks"] = [{"ssid": sent["ssid"], "key": sent.get("key", "")}] + nets
    return cfg


def save(cfg):
    cfg.setdefault("api", DEFAULT_API)
    with open(PATH, "w") as f:
        json.dump(cfg, f)
    try:
        import os
        os.sync()
    except (ImportError, AttributeError, OSError):
        pass
