"""Unit tests for DeepFaceEngine liveness aggregation (mocked DeepFace)."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import numpy as np
import pytest

from app.config import get_settings
from app.services.face.engine import DeepFaceEngine


def _bgr(val: int = 128, *, noise: int = 0) -> np.ndarray:
    """Solid frame; optional noise so consecutive frames are not static duplicates."""
    img = np.full((120, 120, 3), val, dtype=np.uint8)
    if noise:
        rng = np.random.default_rng(noise)
        delta = rng.integers(-8, 9, size=img.shape, dtype=np.int16)
        img = np.clip(img.astype(np.int16) + delta, 0, 255).astype(np.uint8)
    return img


@pytest.fixture(autouse=True)
def _disable_reference_copy_gate(monkeypatch: pytest.MonkeyPatch):
    """Liveness-only tests pass registered_bgr=None; keep diversity on."""
    settings = get_settings()
    monkeypatch.setattr(settings, "face_reject_reference_copy", False)
    monkeypatch.setattr(settings, "face_crop_id_portrait", False)


def test_no_face_frames_excluded_from_liveness_score_and_not_spoof() -> None:
    """Detection failures must not zero-out the mean or mark is_real=False."""
    deepface = MagicMock()

    def extract_faces(**kwargs):
        img = kwargs["img_path"]
        # Dark / first frames: raise (no face); later: live face
        if int(img.mean()) < 40:
            raise ValueError("Face could not be detected in numpy array")
        return [
            {
                "face": img,
                "is_real": True,
                "antispoof_score": 0.85,
            }
        ]

    deepface.extract_faces.side_effect = extract_faces

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=[],
        ):
            # 3/4 frames with face → presence ≥ 0.67; scores only from those 3
            result = DeepFaceEngine().analyze(
                registered_bgr=None,
                live_frames_bgr=[
                    _bgr(10, noise=1),
                    _bgr(180, noise=2),
                    _bgr(180, noise=3),
                    _bgr(180, noise=4),
                ],
            )

    assert result.scored_frame_count == 3
    assert result.liveness_score == 0.85
    assert result.liveness_frame_pass_ratio == 1.0
    assert result.faces_detected_ratio == 0.75
    assert result.liveness_passed is True
    assert result.frame_results[0].is_real is None
    assert result.frame_results[0].antispoof_score is None
    assert result.frame_results[0].faces_detected is False
    assert result.frame_results[1].is_real is True
    assert result.error_code is None


def test_brief_face_flash_fails_presence_not_spoof() -> None:
    """2 live frames of 10 must not pass — presence gate, not spoof labeling."""
    deepface = MagicMock()

    def extract_faces(**kwargs):
        img = kwargs["img_path"]
        if int(img.mean()) < 40:
            raise ValueError("no face")
        return [{"face": img, "is_real": True, "antispoof_score": 0.95}]

    deepface.extract_faces.side_effect = extract_faces
    frames = [_bgr(10, noise=i + 1) for i in range(8)] + [
        _bgr(200, noise=20),
        _bgr(200, noise=21),
    ]

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=[],
        ):
            result = DeepFaceEngine().analyze(
                registered_bgr=None,
                live_frames_bgr=frames,
            )

    assert result.scored_frame_count == 2
    assert result.liveness_score == 0.95
    assert result.liveness_frame_pass_ratio == 1.0
    assert result.faces_detected_ratio == 0.2
    assert result.liveness_passed is False
    assert result.error_code == "insufficient_face_presence"
    assert all(
        fr.is_real is None for fr in result.frame_results if not fr.faces_detected
    )


def test_insufficient_scored_frames_error_code() -> None:
    deepface = MagicMock()
    deepface.extract_faces.side_effect = ValueError("no face")

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=["Image too dark"],
        ):
            result = DeepFaceEngine().analyze(
                registered_bgr=None,
                live_frames_bgr=[_bgr(5, noise=1), _bgr(5, noise=2), _bgr(5, noise=3)],
            )

    assert result.liveness_passed is False
    assert result.scored_frame_count == 0
    assert result.liveness_score is None
    assert result.error_code == "insufficient_liveness_data"


def test_spoof_face_fails_liveness_without_poisoning_absent_frames() -> None:
    deepface = MagicMock()

    def extract_faces(**kwargs):
        img = kwargs["img_path"]
        if int(img.mean()) < 40:
            raise ValueError("no face")
        return [{"face": img, "is_real": False, "antispoof_score": 0.1}]

    deepface.extract_faces.side_effect = extract_faces

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=[],
        ):
            # 3/4 presence so gate is presence-ok; anti-spoof fails instead
            result = DeepFaceEngine().analyze(
                registered_bgr=None,
                live_frames_bgr=[
                    _bgr(10, noise=1),
                    _bgr(200, noise=2),
                    _bgr(200, noise=3),
                    _bgr(200, noise=4),
                ],
            )

    assert result.scored_frame_count == 3
    assert result.faces_detected_ratio == 0.75
    assert result.liveness_passed is False
    assert result.error_code == "liveness_failed"
    assert result.frame_results[0].is_real is None
    assert result.frame_results[1].is_real is False
    assert result.frame_results[1].antispoof_score == 0.1


def test_identical_static_frames_fail_liveness_despite_high_antispoof(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Two identical stills must not pass even if MiniFASNet scores them as real."""
    settings = get_settings()
    monkeypatch.setattr(settings, "face_require_frame_diversity", True)
    monkeypatch.setattr(settings, "face_frame_diversity_min_mad", 2.5)

    deepface = MagicMock()
    deepface.extract_faces.return_value = [
        {"face": _bgr(180), "is_real": True, "antispoof_score": 0.9906}
    ]
    identical = _bgr(180)

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=[],
        ):
            result = DeepFaceEngine().analyze(
                registered_bgr=None,
                live_frames_bgr=[identical, identical.copy()],
            )

    assert result.liveness_passed is False
    assert result.error_code == "static_or_replay_detected"
    assert any("near-identical" in w or "static" in w.lower() for w in result.warnings)


def test_portrait_crop_used_for_registered_id(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Full ID card should be cropped before ArcFace extract/verify."""
    settings = get_settings()
    monkeypatch.setattr(settings, "face_crop_id_portrait", True)
    monkeypatch.setattr(settings, "face_require_frame_diversity", False)
    monkeypatch.setattr(settings, "face_reject_reference_copy", False)

    id_card = np.full((400, 600, 3), 40, dtype=np.uint8)
    portrait_crop = np.full((140, 120, 3), 180, dtype=np.uint8)

    deepface = MagicMock()

    def extract_faces(**kwargs):
        img = kwargs["img_path"]
        # Fail if full card is passed with enforce_detection (simulates the bug)
        if img.shape[0] >= 400:
            raise ValueError("Face could not be detected")
        return [{"face": img, "is_real": True, "antispoof_score": 0.9}]

    deepface.extract_faces.side_effect = extract_faces
    deepface.verify.return_value = {
        "verified": True,
        "distance": 0.25,
        "threshold": 0.68,
        "model": "ArcFace",
    }

    fake_portrait = MagicMock()
    fake_portrait.bgr = portrait_crop
    fake_portrait.method = "haar"
    fake_portrait.face_count = 1

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.engine.extract_portrait",
            return_value=fake_portrait,
        ):
            with patch(
                "app.services.face.image_ops.assess_image_quality",
                return_value=[],
            ):
                result = DeepFaceEngine().analyze(
                    registered_bgr=id_card,
                    live_frames_bgr=[_bgr(190, noise=1), _bgr(195, noise=2)],
                )

    assert result.identity_matched is True
    assert result.distance == 0.25
    assert result.threshold == 0.68
    assert result.match_score is not None
    assert any("portrait cropped" in w.lower() for w in result.warnings)
    # verify must use the crop, not the full card
    verify_img1 = deepface.verify.call_args.kwargs.get("img1_path")
    assert verify_img1 is portrait_crop


def test_identity_match_without_distance_is_rejected(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    settings = get_settings()
    monkeypatch.setattr(settings, "face_crop_id_portrait", False)
    monkeypatch.setattr(settings, "face_require_frame_diversity", False)
    monkeypatch.setattr(settings, "face_reject_reference_copy", False)

    deepface = MagicMock()
    deepface.extract_faces.return_value = [
        {"face": _bgr(180), "is_real": True, "antispoof_score": 0.9}
    ]
    deepface.verify.return_value = {
        "verified": True,
        "distance": None,
        "threshold": None,
        "model": "ArcFace",
    }

    with patch("app.services.face.engine.get_deepface", return_value=deepface):
        with patch(
            "app.services.face.image_ops.assess_image_quality",
            return_value=[],
        ):
            result = DeepFaceEngine().analyze(
                registered_bgr=_bgr(170),
                live_frames_bgr=[_bgr(180, noise=1), _bgr(185, noise=2)],
            )

    assert result.identity_matched is False
    assert result.distance is None
    assert result.match_score is None
    assert result.error_code in {
        "identity_inconclusive",
        "liveness_and_identity_failed",
        "identity_mismatch",
    } or "inconclusive" in " ".join(result.warnings).lower()
