import platform

if platform.system() == "Windows":
    import ctypes
    import winreg

    REG_PATH = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

    def _ensure_windows():
        if platform.system() != "Windows":
            raise RuntimeError("windows only")

    def _read_value(name):
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_READ) as k:
                val, _ = winreg.QueryValueEx(k, name)
                return val
        except Exception:
            return None

    def _set_value(name, value, typ):
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_SET_VALUE) as k:
            winreg.SetValueEx(k, name, 0, typ, value)

    def _delete_value(name):
        try:
            with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_SET_VALUE) as k:
                winreg.DeleteValue(k, name)
        except Exception:
            pass

    def _apply_changes():
        try:
            InternetSetOptionW = ctypes.windll.Wininet.InternetSetOptionW
            InternetSetOptionW(None, 39, None, 0)
            InternetSetOptionW(None, 37, None, 0)
        except Exception:
            pass

    def snapshot_proxy_state():
        _ensure_windows()
        return {
            "ProxyEnable": _read_value("ProxyEnable"),
            "ProxyServer": _read_value("ProxyServer"),
            "ProxyOverride": _read_value("ProxyOverride"),
            "AutoConfigURL": _read_value("AutoConfigURL"),
            "AutoDetect": _read_value("AutoDetect"),
        }

    def enable_system_proxy(port: int, bypass_domains: list[str] | None = None):
        _ensure_windows()
        if not isinstance(port, int) or port <= 0:
            raise ValueError("invalid port")
        bypass = ["localhost", "127.0.0.1"]
        if isinstance(bypass_domains, list):
            for d in bypass_domains:
                s = str(d or "").strip()
                if s:
                    bypass.append(s)
        server = f"http=127.0.0.1:{port};https=127.0.0.1:{port}"
        _set_value("ProxyEnable", 1, winreg.REG_DWORD)
        _set_value("ProxyServer", server, winreg.REG_SZ)
        _set_value("ProxyOverride", ";".join(bypass), winreg.REG_SZ)
        _apply_changes()

    def restore_proxy_state(snapshot: dict | None):
        _ensure_windows()
        if not isinstance(snapshot, dict):
            _set_value("ProxyEnable", 0, winreg.REG_DWORD)
            _delete_value("ProxyServer")
            _delete_value("ProxyOverride")
            _apply_changes()
            return
        pe = snapshot.get("ProxyEnable")
        ps = snapshot.get("ProxyServer")
        po = snapshot.get("ProxyOverride")
        try:
            if pe is None:
                _set_value("ProxyEnable", 0, winreg.REG_DWORD)
            else:
                _set_value("ProxyEnable", int(pe), winreg.REG_DWORD)
        except Exception:
            pass
        if ps is None:
            _delete_value("ProxyServer")
        else:
            _set_value("ProxyServer", str(ps), winreg.REG_SZ)
        if po is None:
            _delete_value("ProxyOverride")
        else:
            _set_value("ProxyOverride", str(po), winreg.REG_SZ)
        _apply_changes()
else:
    def snapshot_proxy_state():
        return {}

    def enable_system_proxy(port: int, bypass_domains: list[str] | None = None):
        raise RuntimeError("windows only")

    def restore_proxy_state(snapshot: dict | None):
        return None
