"""
Lightweight SSL certificate path setup for boto3/requests.

Kept free of s3/server_repo/models imports so early startup (before single-instance
and config watchdog) does not pull the full dependency graph.
"""
import os
import sys
from pathlib import Path

from ws_package.log.writer import LogWriter

logger = LogWriter.file(__name__)


def _find_cacert_pem() -> str | None:
    """Return the path to a valid cacert.pem, preferring the bundled certifi copy."""
    candidates = []

    try:
        import certifi
        candidates.append(certifi.where())
    except Exception:
        pass

    if hasattr(sys, "_MEIPASS"):
        candidates.append(str(Path(sys._MEIPASS) / "certifi" / "cacert.pem"))

    if getattr(sys, "frozen", False):
        candidates.append(
            str(Path(sys.executable).parent / "_internal" / "certifi" / "cacert.pem")
        )

    for path in candidates:
        if path and Path(path).is_file():
            return path

    return None


def setup_ssl_for_boto3() -> bool:
    """Point requests/boto3 at the bundled cacert.pem instead of disabling SSL."""
    try:
        cacert = _find_cacert_pem()
        if cacert:
            os.environ["SSL_CERT_FILE"] = cacert
            os.environ["REQUESTS_CA_BUNDLE"] = cacert
            if "CURL_CA_BUNDLE" not in os.environ:
                os.environ["CURL_CA_BUNDLE"] = cacert
            logger.info("SSL certificates configured: %s", cacert)
        else:
            logger.warning(
                "cacert.pem not found in bundle; HTTPS will use system trust store. "
                "If boto3/requests fail with SSL errors, check certifi is in _internal/."
            )

        logger.info("SSL context configured for boto3")
        return True

    except Exception as e:
        logger.error("Failed to setup SSL for boto3: %s", e)
        return False
