"""One shared `verify=` SSL context for every outbound HTTPS call this
backend makes to a third-party service (an AI provider, Google's reCAPTCHA
verification endpoint, ...). See the module-level comment below for why it
exists and the hard constraint on how it must be used.
"""

import ssl

import truststore

# httpx (like requests) verifies outbound HTTPS against certifi's bundled
# public CA list, not the OS certificate store — so on a machine where
# something locally trusted (a corporate proxy, or antivirus HTTPS
# scanning — e.g. Kaspersky's "Scan encrypted connections" feature) does
# TLS interception, every such call fails with "self-signed certificate in
# certificate chain" even though the OS/browser trusts the connection fine.
#
# Deliberately NOT truststore.inject_into_ssl(): that patches ssl.SSLContext
# for the ENTIRE process, which also hijacks asyncpg's own SSL negotiation
# for the local Postgres connection (asyncpg builds its own ssl.SSLContext
# per connection attempt) — reproduced directly: the background scheduler's
# periodic DB tick (app/core/scheduler.py) started hanging as soon as the
# global patch was in place. A single reusable truststore.SSLContext
# instance, passed explicitly as a client's own `verify=`, gets the same
# OS-trust-store behavior for just the calls that opt into it.
#
# Also deliberately meant to be used via a SYNC httpx.Client inside
# asyncio.to_thread() — NEVER a plain httpx.AsyncClient — everywhere it's
# passed as `verify=`: OS-native certificate verification (what truststore
# uses) can itself block on network I/O — e.g. a CRL/OCSP revocation check —
# and Python's ssl module performs that verification synchronously inside
# the TLS handshake. asyncio's SSL transport calls that handshake step
# directly on the event loop thread, so a slow/stuck verification call
# freezes the ENTIRE process for its duration — every other concurrent
# request, and the scheduler's own DB tick, included. Reproduced directly:
# the live server hung on every request (even /health, no DB involved)
# while a single ai-assistant call was in flight, and the scheduler's
# unrelated DB connection attempts timed out at the same time. Running the
# whole call on a worker thread means only that thread blocks, never the
# event loop other requests depend on. See app/core/ai_client.py and
# app/core/recaptcha.py for the two call sites that follow this.
TRUSTSTORE_SSL_CONTEXT = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
