"""One TLS trust story for every request the app makes.

Reported from a real install, on the update check:

    URLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
    certificate has expired

The server's certificate was fine. What had expired was a root on the
machine doing the asking — the long tail of Windows installs whose trust
store stopped being updated years ago, which still try to chain Let's
Encrypt through a cross-sign that expired in 2021 and fail on every site
using it. Nothing the app does to its own certificate can fix that.

So we trust two things at once:

  * the OS store, which carries whatever a corporate proxy or an antivirus
    with TLS interception has installed — trusting certifi ALONE would
    break every machine behind one of those, and they are common; and
  * certifi's Mozilla set, which is current as of the release and does not
    care how long ago the machine stopped patching.

A certificate needs to satisfy only one of them, so each covers the other's
blind spot. This is also why we do not simply turn verification off: a
tool that uploads someone's clips has no business doing that.
"""
import ssl
import threading

_lock = threading.Lock()
_ctx = None
_note = ""


def _build():
    ctx = ssl.create_default_context()          # the OS store
    note = "system"
    try:
        import certifi
        ctx.load_verify_locations(certifi.where())
        note = "system+certifi"
    except Exception as e:                                      # noqa: BLE001
        note = f"system only ({type(e).__name__})"
    return ctx, note


def context():
    """The shared context. Built once — parsing a CA bundle per request is
    real work, and every caller wants the same answer."""
    global _ctx, _note
    if _ctx is None:
        with _lock:
            if _ctx is None:
                _ctx, _note = _build()
    return _ctx


def trust_note() -> str:
    """What the self-test and the problems pane report."""
    context()
    return _note
