"""
cert_trust/bootstrap.py

This module is imported automatically at Python startup via the .pth file.
It injects system CA certificates into the default SSL context.

Supports two backends:
  1. truststore (Python 3.10+) – Uses OS native cert stores directly.
  2. certifi fallback – Merges system certs with certifi bundle.

The CERT_TRUST_DISABLED environment variable can disable this behavior.
"""
import os
import sys

# Check if disabled via environment variable
if not os.environ.get("CERT_TRUST_DISABLED", "").lower() in ("1", "true", "yes"):
    # Only inject if not disabled
    # Try truststore first (preferred on Python 3.10+)
    try:
        import truststore
        truststore.inject_into_ssl()
    except ImportError:
        # Fallback: try to use certifi with system certs
        try:
            import ssl
            import certifi
            
            # Get the certifi CA bundle path
            certifi_bundle = certifi.where()
            
            # Override the default SSL context to use certifi's bundle
            # This allows certifi to work with any custom certs we've added
            _create_default_context = ssl.create_default_context
            
            def _patched_create_default_context(purpose=ssl.Purpose.SERVER_AUTH, *args, **kwargs):
                ctx = _create_default_context(purpose, *args, **kwargs)
                ctx.load_verify_locations(cafile=certifi_bundle)
                return ctx
            
            ssl.create_default_context = _patched_create_default_context
            ssl._create_default_https_context = _patched_create_default_context
            
        except ImportError:
            # Neither truststore nor certifi available - do nothing
            # Python will use its default behavior
            pass
