# edited by glg
from importlib import import_module
from typing import Any, Dict


class NetworkProbeAdapterService:
    """
    Adapter agar modul sinkronisasi tidak import langsung modul auth.
    Default implementation tetap memakai NetworkProbeService dari auth,
    tetapi dimuat lazy lewat importlib.
    """

    RAW_SERVER_OK = "SERVER_OK"
    RAW_INTERNET_ONLY = "INTERNET_ONLY"
    RAW_OFFLINE = "OFFLINE"

    def __init__(self, probe_service=None, probe_factory=None):
        self.probe_service = probe_service
        self.probe_factory = probe_factory

    def _build_probe_service(self):
        if self.probe_service is not None:
            return self.probe_service

        if callable(self.probe_factory):
            self.probe_service = self.probe_factory()
            return self.probe_service

        module = import_module("pypos.modules.auth.services.network_probe_service")
        probe_cls = getattr(module, "NetworkProbeService")
        self.probe_service = probe_cls()
        return self.probe_service

    def probe_network_snapshot(self, policy: Dict[str, Any] = None) -> Dict[str, Any]:
        service = self._build_probe_service()
        if not hasattr(service, "probe_network_snapshot"):
            raise RuntimeError("Probe service tidak mendukung probe_network_snapshot().")

        snapshot = service.probe_network_snapshot(policy=policy)
        if isinstance(snapshot, dict):
            return snapshot
        return {
            "raw_state": self.RAW_OFFLINE,
            "server": {},
            "internet": {},
            "server_online": False,
            "internet_online": False,
        }
