"""Thread-safe lazy import of DeepFace (and thus TensorFlow).

Ordinary API startup must not import DeepFace/TF. First face/video/ID path that
needs the stack calls ``get_deepface()`` once; concurrent callers share one import.
"""

from __future__ import annotations

import logging
import threading
from typing import Any

logger = logging.getLogger(__name__)

_lock = threading.Lock()
_deepface_api: Any | None = None
_import_error: BaseException | None = None
_import_attempts: int = 0


def is_deepface_loaded() -> bool:
    return _deepface_api is not None


def deepface_import_attempts() -> int:
    """How many times the import path ran (successful or failed). Tests only."""
    return _import_attempts


def reset_deepface_lazy_state_for_tests() -> None:
    """Reset lazy state — for unit tests only. Does not unload TensorFlow from sys.modules."""
    global _deepface_api, _import_error, _import_attempts
    with _lock:
        _deepface_api = None
        _import_error = None
        _import_attempts = 0


def get_deepface() -> Any:
    """Return the DeepFace API object, importing it at most once per process.

    Raises:
        RuntimeError: if deepface is not installed or import fails.
    """
    global _deepface_api, _import_error, _import_attempts

    if _deepface_api is not None:
        return _deepface_api
    if _import_error is not None:
        raise RuntimeError(
            "deepface previously failed to import — "
            "pip install deepface opencv-python-headless tf-keras"
        ) from _import_error

    with _lock:
        if _deepface_api is not None:
            return _deepface_api
        if _import_error is not None:
            raise RuntimeError(
                "deepface previously failed to import — "
                "pip install deepface opencv-python-headless tf-keras"
            ) from _import_error

        _import_attempts += 1
        try:
            from deepface import DeepFace

            _deepface_api = DeepFace
            logger.info("DeepFace stack imported (lazy; attempt=%s)", _import_attempts)
            return _deepface_api
        except ImportError as exc:
            _import_error = exc
            logger.warning("DeepFace import failed: %s", exc)
            raise RuntimeError(
                "deepface is not installed — pip install deepface opencv-python-headless tf-keras"
            ) from exc
        except Exception as exc:  # noqa: BLE001
            _import_error = exc
            logger.exception("DeepFace import crashed")
            raise RuntimeError(
                f"DeepFace failed to initialize: {type(exc).__name__}: {exc}"
            ) from exc
