"""Validate DeepFace / ArcFace / anti-spoof stack for production use."""

from __future__ import annotations

import importlib
import importlib.util
import logging
import sys
from dataclasses import dataclass, field
from functools import lru_cache

logger = logging.getLogger(__name__)


@dataclass
class FaceStackStatus:
    ok: bool
    deepface: bool = False
    opencv: bool = False
    tensorflow: bool = False
    arcface_supported: bool = False
    antispoof_supported: bool = False
    deepface_version: str | None = None
    missing: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    detail: str | None = None

    def raise_if_invalid(self) -> None:
        if self.ok:
            return
        parts = ", ".join(self.missing) if self.missing else "unknown"
        raise RuntimeError(
            f"Face verification stack incomplete ({parts}). "
            "Install: pip install deepface opencv-python-headless tf-keras"
        )


def _module_findable(name: str) -> bool:
    """True if *name* can be imported without raising.

    ``importlib.util.find_spec`` raises ``ValueError`` when a prior test left
    ``sys.modules[name]`` with ``__spec__ is None`` (e.g. bare ModuleType stub).
    Treat that as findable so probes never crash the request path.
    """
    try:
        return importlib.util.find_spec(name) is not None
    except ValueError:
        return name in sys.modules and sys.modules[name] is not None
    except (ImportError, ModuleNotFoundError):
        return False


def probe_face_stack(*, model_name: str = "ArcFace") -> FaceStackStatus:
    """Best-effort dependency probe (no weight download)."""
    missing: list[str] = []
    warnings: list[str] = []
    opencv_ok = False
    deepface_ok = False
    tf_ok = False
    arcface_ok = False
    antispoof_ok = False
    version: str | None = None

    try:
        import cv2  # noqa: F401

        opencv_ok = True
    except ImportError:
        missing.append("opencv-python-headless")

    # Probe TF without importing heavy modules.
    if _module_findable("tensorflow"):
        tf_ok = True
    elif _module_findable("tf_keras"):
        tf_ok = True
        warnings.append("Using tf_keras without tensorflow import")
    else:
        missing.append("tensorflow/tf-keras")

    # Probe deepface without importing (weights / TF side effects).
    if _module_findable("deepface"):
        deepface_ok = True
        version = None  # Version detection omitted to avoid import side effects.
        arcface_ok = True
        antispoof_ok = True
    else:
        missing.append("deepface")
        deepface_ok = False
        arcface_ok = False
        antispoof_ok = False

    ok = (
        opencv_ok
        and deepface_ok
        and tf_ok
        and arcface_ok
        and antispoof_ok
        and not any(m in missing for m in ("deepface", "opencv-python-headless", "tensorflow/tf-keras"))
    )
    # If only tf missing but deepface imported, still often works with tf_keras
    if deepface_ok and opencv_ok and antispoof_ok and not tf_ok:
        ok = False

    detail = (
        "DeepFace ArcFace + anti-spoof ready"
        if ok
        else f"Missing: {', '.join(missing) or 'incomplete stack'}"
    )
    return FaceStackStatus(
        ok=ok,
        deepface=deepface_ok,
        opencv=opencv_ok,
        tensorflow=tf_ok,
        arcface_supported=arcface_ok,
        antispoof_supported=antispoof_ok,
        deepface_version=version,
        missing=missing,
        warnings=warnings,
        detail=detail,
    )


@lru_cache
def get_face_stack_status() -> FaceStackStatus:
    from app.config import get_settings

    settings = get_settings()
    return probe_face_stack(model_name=settings.face_verification_model or "ArcFace")


def clear_face_stack_cache() -> None:
    get_face_stack_status.cache_clear()


def require_face_stack(*, skip_if_engine_override: bool = True) -> FaceStackStatus:
    """Raise RuntimeError when production stack is incomplete.

    Skips when a test FakeEngine is injected.
    """
    if skip_if_engine_override:
        from app.services.face.engine import _engine_override

        if _engine_override is not None:
            return FaceStackStatus(ok=True, detail="test engine override")

    from app.config import get_settings

    settings = get_settings()
    if not bool(getattr(settings, "face_validate_deps", True)):
        return FaceStackStatus(ok=True, detail="face_validate_deps=false")

    status = get_face_stack_status()
    status.raise_if_invalid()
    return status
