"""DeepFace ArcFace verification + MiniFASNet anti-spoofing engine.

Identity matching and liveness are evaluated independently and returned as
separate results. Overall pass is the caller's responsibility (typically AND).
"""

from __future__ import annotations

import logging
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any

import numpy as np

from app.config import get_settings
from app.services.face.lazy_deepface import get_deepface
from app.services.face.portrait import (
    extract_portrait,
    live_frames_are_static_replay,
    live_matches_reference_too_closely,
)

logger = logging.getLogger(__name__)


@dataclass
class FrameAnalysis:
    face_count: int
    is_real: bool | None
    antispoof_score: float | None
    quality_warnings: list[str] = field(default_factory=list)
    error: str | None = None
    faces_detected: bool = False


@dataclass
class FaceEngineResult:
    identity_matched: bool | None  # None = not evaluated (no registered photo)
    distance: float | None
    threshold: float | None
    match_score: float | None
    liveness_passed: bool
    liveness_score: float | None
    liveness_frame_pass_ratio: float | None = None
    model: str = "ArcFace"
    detector: str = "opencv"
    face_count: int | None = None
    frame_results: list[FrameAnalysis] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    error_code: str | None = None
    provider: str = "deepface"
    faces_detected_ratio: float | None = None
    multi_face_frames: int = 0
    scored_frame_count: int = 0


class FaceAnalysisEngine(ABC):
    name: str = "face"

    @abstractmethod
    def analyze(
        self,
        *,
        registered_bgr: np.ndarray | None,
        live_frames_bgr: list[np.ndarray],
    ) -> FaceEngineResult:
        ...


class DeepFaceEngine(FaceAnalysisEngine):
    """Production engine: ArcFace match + DeepFace anti-spoofing (not blink)."""

    name = "deepface"

    def analyze(
        self,
        *,
        registered_bgr: np.ndarray | None,
        live_frames_bgr: list[np.ndarray],
    ) -> FaceEngineResult:
        settings = get_settings()
        model = settings.face_verification_model
        detector = settings.face_detector_backend
        distance_metric = settings.face_distance_metric
        custom_threshold = settings.face_match_distance_threshold
        liveness_min = float(settings.face_liveness_score_threshold)
        min_live_ratio = float(settings.face_liveness_frame_pass_ratio)
        min_presence_ratio = float(settings.face_min_presence_ratio)
        require_single = bool(settings.face_require_single_face)

        DeepFace = get_deepface()
        from app.services.face.image_ops import assess_image_quality

        warnings: list[str] = []
        frame_results: list[FrameAnalysis] = []
        # Only frames with a single detected face and an anti-spoof score
        scored_pass_flags: list[bool] = []
        scored_scores: list[float] = []
        # Per-input-frame score used when picking an identity candidate (0 if unscored)
        candidate_scores: list[float] = []
        faces_detected_flags: list[bool] = []
        multi_face_frames = 0
        min_scored = int(settings.face_min_live_frames)

        if not live_frames_bgr:
            return FaceEngineResult(
                identity_matched=False if registered_bgr is not None else None,
                distance=None,
                threshold=custom_threshold,
                match_score=None,
                liveness_passed=False,
                liveness_score=None,
                liveness_frame_pass_ratio=None,
                model=model,
                detector=detector,
                face_count=None,
                warnings=["No live frames provided"],
                error_code="no_live_frames",
                provider=self.name,
                scored_frame_count=0,
            )

        # --- Registered photo (optional; required only for identity) ---
        # ID cards: crop portrait first so ArcFace sees a face-sized image, not
        # a full document where opencv detector often fails with enforce_detection.
        registered_ok = True
        reference_bgr = registered_bgr
        if registered_bgr is not None and bool(settings.face_crop_id_portrait):
            portrait = extract_portrait(
                registered_bgr,
                detector_backend=detector,
                padding=float(settings.face_portrait_padding),
            )
            if portrait is not None:
                reference_bgr = portrait.bgr
                warnings.append(
                    f"ID portrait cropped via {portrait.method} "
                    f"(faces_seen={portrait.face_count})"
                )
                if require_single and portrait.face_count > 1:
                    registered_ok = False
                    warnings.append(
                        f"Registered photo must contain exactly 1 face "
                        f"(got {portrait.face_count})"
                    )
            else:
                logger.info("Portrait crop found no face; falling back to full image")

        if registered_bgr is not None and registered_ok:
            try:
                reg_faces = DeepFace.extract_faces(
                    img_path=reference_bgr,
                    detector_backend=detector,
                    enforce_detection=True,
                    align=True,
                    anti_spoofing=False,
                )
            except Exception as exc:  # noqa: BLE001
                logger.info("Registered face detection failed: %s", type(exc).__name__)
                # Retry once on full image if we already cropped (crop may be wrong)
                if reference_bgr is not registered_bgr:
                    try:
                        reg_faces = DeepFace.extract_faces(
                            img_path=registered_bgr,
                            detector_backend=detector,
                            enforce_detection=True,
                            align=True,
                            anti_spoofing=False,
                        )
                        reference_bgr = registered_bgr
                        warnings.append(
                            "Portrait crop unused — matched against full ID image"
                        )
                    except Exception as exc2:  # noqa: BLE001
                        logger.info(
                            "Full-image registered face detection failed: %s",
                            type(exc2).__name__,
                        )
                        registered_ok = False
                        warnings.append("No face detected in registered photo")
                        reg_faces = []
                else:
                    registered_ok = False
                    warnings.append("No face detected in registered photo")
                    reg_faces = []

            if not isinstance(reg_faces, list):
                reg_faces = []
            if registered_ok and require_single and len(reg_faces) != 1:
                registered_ok = False
                warnings.append(
                    f"Registered photo must contain exactly 1 face (got {len(reg_faces)})"
                )

        # --- Static / replay gates (before anti-spoof so identical stills cannot pass) ---
        static_replay = False
        if bool(settings.face_require_frame_diversity) and len(live_frames_bgr) >= 2:
            min_mad = float(settings.face_frame_diversity_min_mad)
            if live_frames_are_static_replay(
                live_frames_bgr, min_mean_abs_diff=min_mad
            ):
                static_replay = True
                warnings.append(
                    "Live frames are near-identical — static photo or replay suspected "
                    f"(mean abs diff < {min_mad})"
                )
        if (
            not static_replay
            and registered_bgr is not None
            and bool(settings.face_reject_reference_copy)
        ):
            min_mad = float(settings.face_frame_diversity_min_mad)
            ref_for_copy = reference_bgr if reference_bgr is not None else registered_bgr
            if live_matches_reference_too_closely(
                ref_for_copy, live_frames_bgr, min_mean_abs_diff=min_mad
            ):
                static_replay = True
                warnings.append(
                    "Live frame is a near copy of the registered/ID photo — "
                    "print or file replay suspected"
                )

        # --- Live frames: detection + anti-spoof (always, independent of identity) ---
        for idx, frame in enumerate(live_frames_bgr):
            qw = assess_image_quality(
                frame,
                min_width=int(settings.face_min_width),
                min_height=int(settings.face_min_height),
                min_laplacian_var=float(settings.face_min_laplacian_var),
                min_brightness=float(settings.face_min_brightness),
                max_brightness=float(settings.face_max_brightness),
            )
            try:
                faces = DeepFace.extract_faces(
                    img_path=frame,
                    detector_backend=detector,
                    enforce_detection=True,
                    align=True,
                    anti_spoofing=True,
                )
            except Exception as exc:  # noqa: BLE001
                msg = str(exc)
                logger.info("Live frame %s face extract failed: %s", idx, type(exc).__name__)
                # Detection failure ≠ spoof — leave anti-spoof fields unevaluated
                frame_results.append(
                    FrameAnalysis(
                        face_count=0,
                        is_real=None,
                        antispoof_score=None,
                        quality_warnings=qw,
                        error=msg[:200],
                        faces_detected=False,
                    )
                )
                faces_detected_flags.append(False)
                candidate_scores.append(0.0)
                continue

            if not isinstance(faces, list):
                faces = []
            face_count = len(faces)
            detected = face_count >= 1
            faces_detected_flags.append(detected)
            if face_count > 1:
                multi_face_frames += 1

            if face_count == 0:
                frame_results.append(
                    FrameAnalysis(
                        face_count=0,
                        is_real=None,
                        antispoof_score=None,
                        quality_warnings=qw,
                        error="no_face_detected",
                        faces_detected=False,
                    )
                )
                candidate_scores.append(0.0)
                continue

            if require_single and face_count != 1:
                # Multi-face / empty policy fail — not an anti-spoof determination
                frame_results.append(
                    FrameAnalysis(
                        face_count=face_count,
                        is_real=None,
                        antispoof_score=None,
                        quality_warnings=qw
                        + [f"Expected exactly 1 face, found {face_count}"],
                        error="invalid_face_count",
                        faces_detected=detected,
                    )
                )
                candidate_scores.append(0.0)
                continue

            face = faces[0]
            is_real = face.get("is_real")
            score = face.get("antispoof_score")
            try:
                score_f = float(score) if score is not None else None
            except (TypeError, ValueError):
                score_f = None
            real: bool | None = bool(is_real) if is_real is not None else None
            if score_f is None and real is None:
                # Face found but anti-spoof unavailable — insufficient for this frame
                frame_results.append(
                    FrameAnalysis(
                        face_count=face_count,
                        is_real=None,
                        antispoof_score=None,
                        quality_warnings=qw + ["Anti-spoof score unavailable"],
                        error="antispoof_unavailable",
                        faces_detected=True,
                    )
                )
                candidate_scores.append(0.0)
                continue

            effective_real = bool(real) if real is not None else False
            score_ok = score_f is not None and score_f >= liveness_min
            # If model omitted is_real, fall back to score-only gate
            if real is None:
                passed = score_ok
                effective_real = score_ok
            else:
                passed = effective_real and score_ok
            if qw:
                warnings.extend([f"frame[{idx}]: {w}" for w in qw])
                if bool(settings.face_reject_on_quality_warnings):
                    passed = False

            frame_results.append(
                FrameAnalysis(
                    face_count=face_count,
                    is_real=effective_real,
                    antispoof_score=score_f,
                    quality_warnings=qw,
                    faces_detected=True,
                )
            )
            scored_pass_flags.append(passed)
            scored_scores.append(
                score_f if score_f is not None else (1.0 if effective_real else 0.0)
            )
            candidate_scores.append(scored_scores[-1])

        scored_count = len(scored_scores)
        pass_ratio = (
            sum(1 for p in scored_pass_flags if p) / max(1, scored_count)
            if scored_count
            else 0.0
        )
        liveness_score = float(np.mean(scored_scores)) if scored_scores else 0.0
        faces_detected_ratio = (
            sum(1 for d in faces_detected_flags if d) / max(1, len(faces_detected_flags))
        )

        insufficient = scored_count < min_scored
        presence_ok = faces_detected_ratio >= min_presence_ratio
        antispoof_ok = pass_ratio >= min_live_ratio and liveness_score >= liveness_min
        # Presence is gated separately from anti-spoof so no-face ≠ spoof,
        # but brief face flashes cannot pass overall liveness.
        # Static/replay stills must never pass even if MiniFASNet scores high.
        liveness_passed = (
            not static_replay
            and not insufficient
            and presence_ok
            and antispoof_ok
        )

        if static_replay:
            warnings.append("Liveness failed — static or replay capture detected")
        elif insufficient:
            warnings.append(
                f"Insufficient face frames for liveness "
                f"(scored={scored_count}, need ≥{min_scored})"
            )
        elif not presence_ok:
            warnings.append(
                f"Face presence too low for liveness "
                f"(faces_detected_ratio={faces_detected_ratio:.2f}, "
                f"need ≥{min_presence_ratio})"
            )
        elif not liveness_passed:
            warnings.append(
                f"Liveness failed (pass_ratio={pass_ratio:.2f}, "
                f"score={liveness_score:.3f}, need ratio>={min_live_ratio} "
                f"and score>={liveness_min}; scored_frames={scored_count})"
            )

        # --- Identity: ArcFace (independent of liveness outcome) ---
        identity_matched: bool | None = None
        distance: float | None = None
        threshold: float | None = (
            float(custom_threshold) if custom_threshold is not None else None
        )
        match_score: float | None = None
        identity_error: str | None = None

        if registered_bgr is None:
            identity_matched = None
        elif not registered_ok:
            identity_matched = False
            identity_error = (
                "no_face_registered"
                if "No face detected in registered" in " ".join(warnings)
                else "invalid_face_count_registered"
            )
        else:
            # Prefer best liveness-passing scored frame; else highest antispoof score
            candidate_idxs = [
                i
                for i, fr in enumerate(frame_results)
                if fr.faces_detected
                and fr.antispoof_score is not None
                and fr.is_real is True
                and float(fr.antispoof_score) >= liveness_min
            ]
            if not candidate_idxs:
                candidate_idxs = [
                    i for i, fr in enumerate(frame_results) if fr.faces_detected
                ]
            if not candidate_idxs:
                candidate_idxs = list(range(len(live_frames_bgr)))
            best_idx = max(
                candidate_idxs,
                key=lambda i: candidate_scores[i] if i < len(candidate_scores) else 0.0,
            )
            best_frame = live_frames_bgr[best_idx]
            try:
                verify_kwargs: dict[str, Any] = {
                    "img1_path": reference_bgr,
                    "img2_path": best_frame,
                    "model_name": model,
                    "detector_backend": detector,
                    "distance_metric": distance_metric,
                    "enforce_detection": True,
                    "align": True,
                    "anti_spoofing": False,
                    "silent": True,
                }
                if custom_threshold is not None:
                    verify_kwargs["threshold"] = float(custom_threshold)
                result = DeepFace.verify(**verify_kwargs)
                distance = (
                    float(result.get("distance"))
                    if result.get("distance") is not None
                    else None
                )
                threshold = (
                    float(result.get("threshold"))
                    if result.get("threshold") is not None
                    else custom_threshold
                )
                matched = bool(result.get("verified"))
                # Never claim a match without ArcFace distance + threshold evidence
                if distance is None or threshold is None or threshold <= 0:
                    identity_matched = False
                    identity_error = "identity_inconclusive"
                    match_score = None
                    warnings.append(
                        "Identity match inconclusive — ArcFace distance/threshold missing"
                    )
                else:
                    match_score = max(
                        0.0, min(1.0, 1.0 - (distance / (2.0 * threshold)))
                    )
                    identity_matched = matched
                    model = str(result.get("model") or model)
                    if not matched:
                        warnings.append(
                            f"Identity mismatch (distance={distance}, threshold={threshold})"
                        )
                        identity_error = "identity_mismatch"
            except Exception as exc:  # noqa: BLE001
                logger.info("ArcFace verify failed: %s", type(exc).__name__)
                identity_matched = False
                identity_error = "identity_verify_failed"
                warnings.append(f"Identity verify error: {type(exc).__name__}")

        # Combined error_code: preserve both failure modes
        error_code: str | None = None
        if static_replay:
            liveness_error = "static_or_replay_detected"
        elif insufficient:
            liveness_error = "insufficient_liveness_data"
        elif not presence_ok:
            liveness_error = "insufficient_face_presence"
        elif not liveness_passed:
            liveness_error = "liveness_failed"
        else:
            liveness_error = None
        if liveness_error and identity_matched is False:
            error_code = "liveness_and_identity_failed"
        elif liveness_error:
            error_code = liveness_error
        elif identity_matched is False:
            error_code = identity_error or "identity_mismatch"

        return FaceEngineResult(
            identity_matched=identity_matched,
            distance=round(distance, 6) if distance is not None else None,
            threshold=round(threshold, 6) if threshold is not None else None,
            match_score=round(match_score, 4) if match_score is not None else None,
            liveness_passed=liveness_passed,
            liveness_score=round(liveness_score, 4) if scored_scores else None,
            liveness_frame_pass_ratio=round(pass_ratio, 4) if scored_scores else None,
            model=model,
            detector=detector,
            face_count=frame_results[0].face_count if frame_results else None,
            frame_results=frame_results,
            warnings=warnings,
            error_code=error_code,
            provider=self.name,
            faces_detected_ratio=round(faces_detected_ratio, 4),
            multi_face_frames=multi_face_frames,
            scored_frame_count=scored_count,
        )


_engine_override: FaceAnalysisEngine | None = None
_engine_lock = threading.Lock()
_engine_singleton: FaceAnalysisEngine | None = None


def set_face_engine_override(engine: FaceAnalysisEngine | None) -> None:
    """Test helper to inject a fake engine without DeepFace weights."""
    global _engine_override, _engine_singleton
    with _engine_lock:
        _engine_override = engine
        # Drop cached production engine when tests inject/clear overrides
        if engine is not None:
            _engine_singleton = None


def get_face_engine() -> FaceAnalysisEngine:
    """Return the process-wide face engine (override in tests, else DeepFaceEngine).

    Creating DeepFaceEngine does not import TensorFlow; DeepFace loads on first
    ``analyze()`` via ``get_deepface()``.
    """
    global _engine_singleton
    if _engine_override is not None:
        return _engine_override
    if _engine_singleton is not None:
        return _engine_singleton
    with _engine_lock:
        if _engine_override is not None:
            return _engine_override
        if _engine_singleton is not None:
            return _engine_singleton
        settings = get_settings()
        provider = (settings.face_verification_provider or "deepface").lower()
        if provider in {"deepface", "arcface"}:
            _engine_singleton = DeepFaceEngine()
            return _engine_singleton
        raise RuntimeError(
            f"Unsupported face_verification_provider={provider!r}; use 'deepface'"
        )
