from __future__ import annotations

import ssl
from urllib.request import urlopen


_SSL_CONTEXT: ssl.SSLContext | None = None


def default_ssl_context() -> ssl.SSLContext | None:
    global _SSL_CONTEXT
    if _SSL_CONTEXT is not None:
        return _SSL_CONTEXT
    try:
        import certifi

        _SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
        return _SSL_CONTEXT
    except Exception:
        return None


def open_url(request, *, timeout: float | int):
    context = default_ssl_context()
    if context is not None:
        return urlopen(request, timeout=timeout, context=context)
    return urlopen(request, timeout=timeout)
