from __future__ import annotations

import ssl
import urllib.request
from pathlib import Path
from typing import Any

HttpOpener = Any


def ssl_context() -> ssl.SSLContext:
    """Build TLS context with a reliable CA bundle (python.org macOS often lacks one)."""
    try:
        import certifi

        return ssl.create_default_context(cafile=certifi.where())
    except ImportError:
        pass
    for cafile in ("/etc/ssl/cert.pem", "/private/etc/ssl/cert.pem"):
        if Path(cafile).is_file():
            return ssl.create_default_context(cafile=cafile)
    return ssl.create_default_context()


def default_urlopen(req: urllib.request.Request, *, timeout: float = 30) -> Any:
    return urllib.request.urlopen(req, timeout=timeout, context=ssl_context())
