"""Small, read-only GenieACS NBI client for customer ONT integration."""
from __future__ import annotations

import base64
import json
import os
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen


class GenieACSUnavailable(RuntimeError):
    pass


def _base_url() -> str:
    return os.getenv("GENIEACS_NBI_URL", "http://127.0.0.1:7557").rstrip("/")


def _request(path: str, *, query: dict | None = None, body: dict | None = None, timeout: int = 8, base_url: str | None = None):
    url = (base_url or _base_url()).rstrip("/") + path
    if query is not None:
        url += "?" + urlencode({"query": json.dumps(query, separators=(",", ":"))})
    headers = {"Accept": "application/json"}
    username = os.getenv("GENIEACS_NBI_USERNAME")
    password = os.getenv("GENIEACS_NBI_PASSWORD")
    if username and password:
        token = base64.b64encode(f"{username}:{password}".encode()).decode()
        headers["Authorization"] = f"Basic {token}"
    data = json.dumps(body).encode() if body is not None else None
    if data is not None:
        headers["Content-Type"] = "application/json"
    request = Request(url, data=data, headers=headers, method="POST" if data is not None else "GET")
    try:
        with urlopen(request, timeout=timeout) as response:
            payload = response.read()
            return response.status, json.loads(payload) if payload else None
    except HTTPError as exc:
        try:
            payload = exc.read().decode(errors="replace")[:300]
        except Exception:
            payload = ""
        raise GenieACSUnavailable(f"GenieACS NBI HTTP {exc.code}: {payload}") from exc
    except (URLError, TimeoutError, OSError, ValueError) as exc:
        raise GenieACSUnavailable(f"GenieACS NBI tidak dapat dijangkau: {exc}") from exc


def _device_for_serial(serial_number: str, *, base_url: str | None = None) -> dict | None:
    serial = (serial_number or "").strip().upper()
    if not serial:
        return None
    _, records = _request("/devices/", query={"_deviceId._SerialNumber": serial}, base_url=base_url)
    if not isinstance(records, list):
        raise GenieACSUnavailable("Respons GenieACS NBI tidak valid.")
    return records[0] if records else None


def _walk_values(node, path=""):
    if isinstance(node, dict):
        if "_value" in node:
            yield path, node.get("_value")
            return
        for key, value in node.items():
            yield from _walk_values(value, f"{path}.{key}" if path else key)
    elif isinstance(node, list):
        for value in node:
            yield from _walk_values(value, path)


_DHCP_SERVER_PARAMETERS = (
    # TR-098 InternetGatewayDevice model used by many ONTs.
    "InternetGatewayDevice.LANDevice.1.LANHostConfigManagement.DHCPServerEnable",
    # TR-181 Device model exposed by newer ONTs.
    "Device.DHCPv4.Server.1.Enable",
)


def _parameter_node(device: dict, wanted: str) -> dict | None:
    def walk(node, path=""):
        if isinstance(node, dict):
            if "_value" in node:
                return node if path == wanted else None
            for key, child in node.items():
                found = walk(child, f"{path}.{key}" if path else key)
                if found is not None:
                    return found
        elif isinstance(node, list):
            for child in node:
                found = walk(child, path)
                if found is not None:
                    return found
        return None

    return walk(device)


def _dhcp_server_state(device: dict) -> dict:
    readonly_fallback = None
    for path in _DHCP_SERVER_PARAMETERS:
        node = _parameter_node(device, path)
        if node is None:
            continue
        raw = node.get("_value")
        if isinstance(raw, bool):
            enabled = raw
        elif str(raw).strip().casefold() in {"1", "true", "enabled"}:
            enabled = True
        elif str(raw).strip().casefold() in {"0", "false", "disabled"}:
            enabled = False
        else:
            enabled = None
        state = {
            "available": enabled is not None,
            "enabled": enabled,
            "writable": node.get("_writable") is True,
            "parameter": path,
        }
        if enabled is None:
            continue
        if state["writable"]:
            return state
        if readonly_fallback is None:
            readonly_fallback = state
    return readonly_fallback or {"available": False, "enabled": None, "writable": False, "parameter": None}


def configure_pppoe_wan(serial_number: str, *, username: str, password: str, vlan: int, nbi_url: str | None = None, wait_seconds: int = 75, reuse_vlan: bool = False) -> dict:
    """Idempotently ensure a TR-069 WAN PPP connection through GenieACS."""
    import re, time
    if not username or not password or not 1 <= int(vlan) <= 4094:
        raise GenieACSUnavailable("Incomplete PPPoE data for ACS configuration.")
    base_url = (nbi_url or "").strip().rstrip("/") or None
    device = _device_for_serial(serial_number, base_url=base_url)
    if not device or not device.get("_id"):
        raise GenieACSUnavailable("ONT is not registered in GenieACS; ACS management path is unavailable.")
    device_id = device["_id"]
    table_re = re.compile(r"^(.*?WANPPPConnection)\.(\d+)\.(.+)$", re.I)
    def rows_for(record):
        rows = {}
        for path, value in _walk_values(record):
            match = table_re.match(path)
            if match: rows.setdefault((match.group(1), match.group(2)), {})[match.group(3)] = value
        return rows
    def parameter(record, wanted):
        def walk(node, path=""):
            if isinstance(node, dict):
                if "_value" in node: return node if path == wanted else None
                for key, child in node.items():
                    found = walk(child, f"{path}.{key}" if path else key)
                    if found is not None: return found
            elif isinstance(node, list):
                for child in node:
                    found = walk(child, path)
                    if found is not None: return found
            return None
        return walk(record)
    def pending_tasks():
        try:
            _, tasks = _request("/tasks/", query={"device": device_id}, base_url=base_url)
        except GenieACSUnavailable as exc:
            raise GenieACSUnavailable("Tidak dapat memeriksa antrean task ACS; pembuatan WAN dihentikan agar tidak duplikat.") from exc
        if not isinstance(tasks, list):
            raise GenieACSUnavailable("Respons antrean task ACS tidak valid; pembuatan WAN dihentikan.")
        return tasks
    def pending_add():
        return any(str(t.get("name", "")).casefold() == "addobject"
                   and "wanpppconnection" in str(t.get("objectName", "")).casefold()
                   for t in pending_tasks() if isinstance(t, dict))
    rows = rows_for(device)
    table = next((k[0] for k in rows), "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection")
    matching = next((k for k,v in rows.items() if str(v.get("Username", "")).strip() == username), None)
    if matching is None and reuse_vlan:
        candidates = [k for k, v in rows.items()
            if str(v.get("X_ZTE-COM_VLANID", "")).strip() == str(int(vlan))
            and str(v.get("ConnectionType", "")).casefold() in {"ip_routed", "routed"}
            and bool(v.get("Enable"))
            and str(v.get("ExternalIPAddress", "")).strip() not in {"", "0.0.0.0"}]
        if len(candidates) != 1:
            raise GenieACSUnavailable("ACS tidak menemukan tepat satu WAN PPPoE aktif pada VLAN layanan; WAN ONT tidak diubah.")
        matching = candidates[0]
    if matching is None:
        matching = next((k for k,v in rows.items() if not str(v.get("Username", "") or "").strip()), None)
        if matching is None:
            if not pending_add():
                path = f"/devices/{quote(device_id, safe='')}/tasks?timeout=5000&connection_request"
                try:
                    _request(path, body={"name": "addObject", "objectName": table + "."}, base_url=base_url)
                except GenieACSUnavailable as exc:
                    raise GenieACSUnavailable("GenieACS gagal menerima task pembuatan WAN PPPoE.") from exc
            deadline = time.monotonic() + max(10, min(int(wait_seconds), 90))
            while time.monotonic() < deadline:
                time.sleep(3)
                device = _device_for_serial(serial_number, base_url=base_url)
                if not device: continue
                rows = rows_for(device)
                matching = next((k for k,v in rows.items() if str(v.get("Username", "")).strip() == username), None)
                if matching is None: matching = next((k for k,v in rows.items() if k[0].casefold() == table.casefold() and not str(v.get("Username", "") or "").strip()), None)
                if matching: break
            if matching is None: raise GenieACSUnavailable("ACS addObject task is waiting for an ONT Inform; held to prevent duplicate WAN objects.")
    table_path, instance = matching
    root = f"{table_path}.{instance}"
    default_service_path = "InternetGatewayDevice.Layer3Forwarding.DefaultConnectionService"
    default_service = parameter(device, default_service_path)
    if default_service is None:
        raise GenieACSUnavailable("ACS does not expose the default routed WAN parameter; refusing to report WAN synchronization as complete.")
    if default_service.get("_writable") is not True:
        raise GenieACSUnavailable("ACS marks the default routed WAN parameter as not writable.")
    default_service_value = f"{table_path}.{instance}"
    fields = [("Enable",True,"xsd:boolean",True),("Username",username,"xsd:string",True),("Password",password,"xsd:string",True),("ConnectionType","IP_Routed","xsd:string",False),("NATEnabled",True,"xsd:boolean",False),("X_ZTE-COM_VLANEnable",True,"xsd:boolean",False),("X_ZTE-COM_VLANID",int(vlan),"xsd:unsignedInt",False)]
    changes = []
    for leaf,value,kind,required in fields:
        path = root+"."+leaf
        node = parameter(device,path)
        if node is None:
            if required: raise GenieACSUnavailable(f"ACS data model does not expose PPPoE parameter {leaf}.")
            continue
        if node.get("_value") == value:
            continue
        if node.get("_writable") is not True:
            if required: raise GenieACSUnavailable(f"ACS marks PPPoE parameter {leaf} as not writable.")
            continue
        changes.append([path,value,kind])
    if default_service.get("_value") != default_service_value:
        changes.append([default_service_path,default_service_value,"xsd:string"])
    pending_config = any(
        str(task.get("name", "")).casefold() == "setparametervalues"
        and any(isinstance(item, list) and item and (str(item[0]).startswith(root + ".") or str(item[0]) == default_service_path) for item in task.get("parameterValues", []))
        for task in pending_tasks() if isinstance(task, dict)
    )
    if changes and not pending_config:
        path = f"/devices/{quote(device_id, safe='')}/tasks?timeout=5000&connection_request"
        try:
            _request(path, body={"name":"setParameterValues","parameterValues":changes}, base_url=base_url)
        except GenieACSUnavailable as exc:
            raise GenieACSUnavailable("GenieACS gagal menerima konfigurasi WAN PPPoE.") from exc
    deadline = time.monotonic() + max(0, min(int(wait_seconds), 90))
    verified = False
    while True:
        latest = _device_for_serial(serial_number, base_url=base_url)
        latest_rows = rows_for(latest or {})
        current = latest_rows.get((table_path, instance), {})
        if (str(current.get("Username", "")).strip() == username
                and bool(current.get("Enable"))
                and bool(current.get("NATEnabled"))
                and str(current.get("X_ZTE-COM_VLANID", "")).strip() == str(int(vlan))
                and str(current.get("ExternalIPAddress", "")).strip() not in {"", "0.0.0.0"}
                and str(current.get("ConnectionStatus", "")).casefold() == "connected"):
            latest_default = parameter(latest or {}, default_service_path)
            if latest_default and latest_default.get("_value") == default_service_value:
                verified = True
                break
        if time.monotonic() >= deadline:
            break
        time.sleep(3)
    return {"accepted":True,"queued":bool(changes) or pending_config,"instance":instance,
            "changed_parameters":len(changes),"connected":verified,
            "message":"ONT PPPoE WAN and default routed connection synchronized via ACS; PPP session and internet are still verified on MikroTik."}


def get_customer_device(serial_number: str) -> dict | None:
    """Return safe status/telemetry; never returns credentials or request URLs."""
    device = _device_for_serial(serial_number)
    if device is None:
        return None
    values = list(_walk_values(device))
    by_path = {path: value for path, value in values}
    optical = []
    markers = ("optical", "rxpower", "receivepower", "signallevel", "receivedpower")
    for path, value in values:
        if any(marker in path.casefold() for marker in markers) and value not in (None, ""):
            optical.append({"parameter": path, "value": value})
    def first(suffixes):
        for path, value in values:
            if any(path.casefold().endswith(s.casefold()) for s in suffixes) and value not in (None, ""):
                return value
        return None
    return {
        "device_id": device.get("_id"),
        "last_inform": device.get("_lastInform"),
        "last_boot": device.get("_lastBoot"),
        "manufacturer": first(("DeviceInfo.Manufacturer", "DeviceInfo.ManufacturerName")),
        "model": first(("DeviceInfo.ModelName",)),
        "serial_number": serial_number,
        "optical_parameters": optical[:20],
        "parameter_count": len(values),
    }


def request_ont_ip_ping(serial_number: str, *, host: str = "1.1.1.1", fresh_minutes: int = 15, result_ttl_seconds: int = 300) -> dict:
    """Use the ONT's TR-098 IPPingDiagnostics as an automatic, customer-free check.

    A stale CPE or a device with an existing task backlog is left untouched so
    this check cannot pile up behind older WiFi/configuration tasks.
    """
    from datetime import datetime, timedelta, timezone

    if host not in {"1.1.1.1", "8.8.8.8"}:
        raise GenieACSUnavailable("Host diagnostik ONT tidak diizinkan.")
    device = _device_for_serial(serial_number)
    if not device or not device.get("_id"):
        return {"status": "unavailable", "detail": "ONT belum terdaftar di GenieACS."}

    def stamp(raw):
        try:
            value = datetime.fromisoformat(str(raw).replace("Z", "+00:00"))
            return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)
        except (TypeError, ValueError):
            return None

    now = datetime.now(timezone.utc)
    last_inform = stamp(device.get("_lastInform"))
    if last_inform is None or now - last_inform > timedelta(minutes=max(1, fresh_minutes)):
        return {"status": "unavailable", "detail": "ONT belum mengirim Inform ACS terbaru; tes otomatis menunggu koneksi GenieACS."}

    prefix = "InternetGatewayDevice.IPPingDiagnostics."
    state_node = _parameter_node(device, prefix + "DiagnosticsState")
    state = str(state_node.get("_value", "")).strip().casefold() if state_node else ""
    diag_stamp = stamp(state_node.get("_timestamp")) if state_node else None
    recent = diag_stamp is not None and now - diag_stamp <= timedelta(seconds=max(30, result_ttl_seconds))
    if recent and state in {"complete", "completed"}:
        success_node = _parameter_node(device, prefix + "SuccessCount")
        failures_node = _parameter_node(device, prefix + "FailureCount")
        try:
            successes = int(success_node.get("_value") or 0) if success_node else 0
            failures = int(failures_node.get("_value") or 0) if failures_node else 0
        except (TypeError, ValueError):
            successes, failures = 0, 0
        return {"status": "success" if successes > 0 else "failed", "success_count": successes,
                "failure_count": failures, "checked_at": diag_stamp.isoformat(),
                "detail": "ONT berhasil ping internet via GenieACS." if successes > 0 else "Tes ping internet dari ONT selesai tanpa balasan."}
    if state.startswith("error_") and recent:
        return {"status": "failed", "checked_at": diag_stamp.isoformat(),
                "detail": "Tes ping ONT gagal: " + state}
    if state == "requested":
        return {"status": "pending", "detail": "ONT sedang menjalankan tes ping internet via GenieACS."}

    device_id = device["_id"]
    _, tasks = _request("/tasks/", query={"device": device_id})
    if not isinstance(tasks, list):
        return {"status": "unavailable", "detail": "Antrean task GenieACS tidak dapat dibaca."}
    if tasks:
        return {"status": "unavailable", "detail": f"Tes ONT ditahan karena ada {len(tasks)} task GenieACS lama yang belum tersinkron."}

    required = {
        "Host": (host, "xsd:string"),
        "NumberOfRepetitions": (3, "xsd:unsignedInt"),
        "Timeout": (2000, "xsd:unsignedInt"),
        "DiagnosticsState": ("Requested", "xsd:string"),
    }
    parameters = []
    for leaf, (value, kind) in required.items():
        node = _parameter_node(device, prefix + leaf)
        if node is None or node.get("_writable") is not True:
            return {"status": "unsupported", "detail": f"ONT tidak menyediakan field diagnostik writable: {leaf}."}
        parameters.append([prefix + leaf, value, kind])

    path = f"/devices/{quote(device_id, safe='')}/tasks?timeout=5000&connection_request"
    try:
        _request(path, body={"name": "setParameterValues", "parameterValues": parameters})
    except GenieACSUnavailable as exc:
        return {"status": "unavailable", "detail": str(exc)[:240]}
    return {"status": "pending", "detail": "Tes ping otomatis dikirim ke ONT; menunggu hasil dari Inform GenieACS."}


def refresh_customer_device(serial_number: str) -> dict:
    """Queue a read-only model refresh and ask GenieACS to connection-request the ONT."""
    device = _device_for_serial(serial_number)
    if device is None:
        raise GenieACSUnavailable("ONT belum terdaftar di GenieACS.")
    device_id = device.get("_id")
    if not device_id:
        raise GenieACSUnavailable("GenieACS tidak mengembalikan ID perangkat.")
    path = f"/devices/{quote(device_id, safe='')}/tasks?timeout=5000&connection_request"
    status, task = _request(path, body={"name": "refreshObject", "objectName": "InternetGatewayDevice"}, timeout=8)
    return {"accepted": status in (200, 202), "queued": status == 202, "task_id": (task or {}).get("_id")}


def _wifi_fields(device: dict) -> list[dict]:
    import re
    fields = {}
    for path, value in _walk_values(device):
        match = re.search(r"(?:WLANConfiguration|SSID|AccessPoint)\.(\d+)\.", path)
        if not match: continue
        leaf = path.rsplit(".", 1)[-1]
        if leaf in ("SSID", "Enable", "KeyPassphrase", "PreSharedKey", "ModeEnabled", "BeaconType", "BasicEncryptionModes", "BasicAuthenticationMode", "IEEE11iEncryptionModes", "IEEE11iAuthenticationMode", "WPAEncryptionModes", "WPAAuthenticationMode"):
            fields[(match.group(1), leaf)] = {"path": path, "value": value}
    profiles = {}
    for (index, leaf), item in fields.items():
        row = profiles.setdefault(index, {"wlan": int(index), "paths": {}, "values": {}})
        row["paths"][leaf] = item["path"]; row["values"][leaf] = item["value"]
    for row in profiles.values():
        row["ssid"] = row["values"].get("SSID"); row["enabled"] = row["values"].get("Enable")
        row["security"] = row["values"].get("ModeEnabled", row["values"].get("BeaconType"))
        secret = row["values"].get("KeyPassphrase", row["values"].get("PreSharedKey"))
        if secret and str(secret).strip() not in ("", "********", "**********"): row["password"] = secret
        row.pop("values", None)
    return sorted(profiles.values(), key=lambda x: x["wlan"])


def get_wifi_configuration(serial_number: str) -> dict:
    device = _device_for_serial(serial_number)
    if device is None: return {"found": False, "message": "ONT not found in GenieACS."}
    dhcp_server = _dhcp_server_state(device)
    rows = _wifi_fields(device)
    if not rows: return {"found": True, "last_inform": device.get("_lastInform"), "data": [], "dhcp_server": dhcp_server, "message": "WLAN parameters are not reported to ACS yet."}
    return {"found": True, "last_inform": device.get("_lastInform"), "data": rows, "dhcp_server": dhcp_server}


def set_dhcp_server_configuration(serial_number: str, *, enabled: bool) -> dict:
    """Queue a LAN DHCP server toggle only when the ONT exposes it as writable."""
    if not isinstance(enabled, bool):
        raise GenieACSUnavailable("DHCP server state must be true or false.")
    device = _device_for_serial(serial_number)
    if device is None:
        raise GenieACSUnavailable("ONT is not registered in GenieACS.")
    device_id = device.get("_id")
    if not device_id:
        raise GenieACSUnavailable("GenieACS did not return a device ID.")
    state = _dhcp_server_state(device)
    if not state["available"]:
        raise GenieACSUnavailable("ACS does not report a supported LAN DHCP server parameter for this ONT.")
    if not state["writable"]:
        raise GenieACSUnavailable("ACS marks the LAN DHCP server parameter as not writable.")
    if state["enabled"] == enabled:
        return {"accepted": True, "queued": False, "changed": False, "enabled": enabled, "parameter": state["parameter"]}
    path = f"/devices/{quote(device_id, safe='')}/tasks?timeout=5000&connection_request"
    status, task = _request(path, body={
        "name": "setParameterValues",
        "parameterValues": [[state["parameter"], enabled, "xsd:boolean"]],
    })
    return {
        "accepted": status in (200, 202), "queued": status == 202,
        "changed": True, "enabled": enabled, "parameter": state["parameter"],
        "task_id": (task or {}).get("_id"),
    }


def set_wifi_configuration(serial_number: str, *, wlan: int, ssid: str | None = None, password: str | None = None, open_network: bool | None = None) -> dict:
    device = _device_for_serial(serial_number)
    if device is None: raise GenieACSUnavailable("ONT is not registered in GenieACS.")
    row = next((item for item in _wifi_fields(device) if item["wlan"] == wlan), None)
    if row is None: raise GenieACSUnavailable(f"WLAN {wlan} is not present in the ACS data model.")
    # Queue changes even when the cached Inform is old. GenieACS will request
    # a connection and apply the task when the ONT becomes reachable.
    def writable(wanted):
        def walk(node, path=""):
            if isinstance(node, dict):
                if "_value" in node and path == wanted: return node.get("_writable") is True
                for key, val in node.items():
                    found = walk(val, f"{path}.{key}" if path else key)
                    if found is not None: return found
            elif isinstance(node, list):
                for val in node:
                    found = walk(val, path)
                    if found is not None: return found
        return walk(device)
    changes = []
    def add_parameter(leaf, value, kind="xsd:string", *, required=True):
        path = row["paths"].get(leaf)
        if not path:
            if required: raise GenieACSUnavailable(f"ACS does not expose required WiFi parameter {leaf}.")
            return
        if not writable(path): raise GenieACSUnavailable(f"ACS marks WiFi parameter {leaf} as not writable.")
        changes.append([path, value, kind])
    if ssid is not None:
        add_parameter("SSID", ssid)
    if open_network is True:
        mode_path = row["paths"].get("ModeEnabled") or row["paths"].get("BeaconType")
        if not mode_path or not writable(mode_path):
            raise GenieACSUnavailable("Writable WiFi security-mode parameter was not found in ACS.")
        is_legacy = mode_path.endswith(".BeaconType")
        changes.append([mode_path, "Basic" if is_legacy else "None", "xsd:string"])
        if is_legacy:
            add_parameter("BasicEncryptionModes", "None")
            add_parameter("BasicAuthenticationMode", "None")
        add_parameter("Enable", True, "xsd:boolean", required=False)
        key = row["paths"].get("KeyPassphrase") or row["paths"].get("PreSharedKey")
        if not key or not writable(key):
            raise GenieACSUnavailable("ACS tidak menyediakan parameter password WLAN yang dapat dikosongkan.")
        changes.append([key, "", "xsd:string"])
    elif open_network is False:
        if not password:
            raise GenieACSUnavailable("Masukkan password WiFi untuk mengaktifkan WPA2.")
        mode_path = row["paths"].get("ModeEnabled") or row["paths"].get("BeaconType")
        if not mode_path or not writable(mode_path):
            raise GenieACSUnavailable("Writable WiFi security-mode parameter was not found in ACS.")
        is_legacy = mode_path.endswith(".BeaconType")
        if is_legacy:
            # Values verified against the selected ZTE WLAN data model.
            add_parameter("IEEE11iEncryptionModes", "AESEncryption")
            add_parameter("IEEE11iAuthenticationMode", "PSKAuthentication")
            changes.append([mode_path, "11i", "xsd:string"])
        else:
            changes.append([mode_path, "WPA2-Personal", "xsd:string"])
        add_parameter("Enable", True, "xsd:boolean", required=False)
        key = row["paths"].get("KeyPassphrase") or row["paths"].get("PreSharedKey")
        if not key or not writable(key):
            raise GenieACSUnavailable("ACS tidak menyediakan parameter password WLAN yang dapat ditulis.")
        changes.append([key, password, "xsd:string"])
    elif password is not None:
        key = row["paths"].get("KeyPassphrase") or row["paths"].get("PreSharedKey")
        if not key or not writable(key): raise GenieACSUnavailable("Writable WLAN password parameter was not found.")
        changes.append([key, password, "xsd:string"])
    if not changes: raise GenieACSUnavailable("No WiFi changes were requested.")
    path = f"/devices/{quote(device.get('_id'), safe='')}/tasks?timeout=5000&connection_request"
    status, task = _request(path, body={"name": "setParameterValues", "parameterValues": changes})
    return {"accepted": status in (200, 202), "queued": status == 202, "task_id": (task or {}).get("_id"), "parameters": [x[0] for x in changes], "wlan": wlan}
