"""Disable SSL verification for corporate networks with SSL inspection proxies.

Call patch_ssl() before any huggingface_hub / httpx / requests calls.
Safe to call multiple times.
"""
from __future__ import annotations

import os

_patched = False


def patch_ssl() -> None:
    """Monkey-patch httpx + ssl to skip certificate verification."""
    global _patched
    if _patched:
        return

    import ssl

    # 1. Patch ssl module functions
    ssl._create_default_https_context = ssl._create_unverified_context

    _orig = ssl.create_default_context
    def _no_verify(*args, **kwargs):
        ctx = _orig(*args, **kwargs)
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        return ctx
    ssl.create_default_context = _no_verify

    # 2. Patch httpx clients directly (huggingface_hub creates these at import time)
    try:
        import httpx

        _orig_client = httpx.Client.__init__
        def _client_init(self, *args, **kwargs):
            kwargs.setdefault("verify", False)
            _orig_client(self, *args, **kwargs)
        httpx.Client.__init__ = _client_init

        _orig_async = httpx.AsyncClient.__init__
        def _async_client_init(self, *args, **kwargs):
            kwargs.setdefault("verify", False)
            _orig_async(self, *args, **kwargs)
        httpx.AsyncClient.__init__ = _async_client_init
    except ImportError:
        pass

    # 3. Environment variables (for requests / curl-based libs)
    os.environ["HF_HUB_DISABLE_SSL_VERIFY"] = "1"
    os.environ["CURL_CA_BUNDLE"] = ""
    os.environ["REQUESTS_CA_BUNDLE"] = ""

    _patched = True
