"""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):
    url = _base_url() + 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) -> dict | None:
    serial = (serial_number or "").strip().upper()
    if not serial:
        return None
    _, records = _request("/devices/", query={"_deviceId._SerialNumber": serial})
    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)


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 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"):
            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."}
    rows = _wifi_fields(device)
    if not rows: return {"found": True, "last_inform": device.get("_lastInform"), "data": [], "message": "WLAN parameters are not reported to ACS yet."}
    return {"found": True, "last_inform": device.get("_lastInform"), "data": rows}


def set_wifi_configuration(serial_number: str, *, wlan: int, ssid: str | None = None, password: str | None = None, open_network: bool = False) -> 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 = []
    if ssid is not None:
        path = row["paths"].get("SSID")
        if not path or not writable(path): raise GenieACSUnavailable("ACS does not mark the SSID parameter writable.")
        changes.append([path, ssid, "xsd:string"])
    if open_network:
        path = row["paths"].get("ModeEnabled") or row["paths"].get("BeaconType")
        if not path or not writable(path): raise GenieACSUnavailable("Writable open-security parameter was not found in ACS.")
        changes.append([path, "Basic" if path.endswith(".BeaconType") else "None", "xsd:string"])
        if path.endswith(".BeaconType"):
            for leaf in ("BasicEncryptionModes", "BasicAuthenticationMode"):
                legacy_path = row["paths"].get(leaf)
                if not legacy_path or not writable(legacy_path):
                    raise GenieACSUnavailable("ACS belum menyediakan parameter enkripsi/authentication yang diperlukan untuk memastikan WLAN benar-benar terbuka.")
                changes.append([legacy_path, "None", "xsd:string"])
        enable = row["paths"].get("Enable")
        if enable:
            if not writable(enable): raise GenieACSUnavailable("WLAN enable flag is not writable in ACS.")
            changes.append([enable, True, "xsd:boolean"])
        key = row["paths"].get("KeyPassphrase") or row["paths"].get("PreSharedKey")
        if key:
            if not writable(key): raise GenieACSUnavailable("WLAN password is not writable in ACS.")
            changes.append([key, "", "xsd:string"])
    elif password is not None:
        path = row["paths"].get("KeyPassphrase") or row["paths"].get("PreSharedKey")
        if not path or not writable(path): raise GenieACSUnavailable("Writable WLAN password parameter was not found.")
        changes.append([path, 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}
