"""Portrait crop + static-replay helpers."""

from __future__ import annotations

import base64

import numpy as np
import pytest

from app.services.face.image_ops import FaceImageError, decode_base64_image
from app.services.face.portrait import (
    extract_portrait,
    frames_mean_abs_diff,
    live_frames_are_static_replay,
)


def test_identical_frames_detected_as_static() -> None:
    a = np.full((80, 80, 3), 100, dtype=np.uint8)
    assert live_frames_are_static_replay([a, a.copy()], min_mean_abs_diff=2.5) is True


def test_noisy_frames_not_static() -> None:
    a = np.full((80, 80, 3), 100, dtype=np.uint8)
    b = np.full((80, 80, 3), 160, dtype=np.uint8)
    assert frames_mean_abs_diff(a, b) > 2.5
    assert live_frames_are_static_replay([a, b], min_mean_abs_diff=2.5) is False


def test_extract_portrait_haar_on_synthetic_face() -> None:
    """Draw a simple face-like blob Haar can find on a larger 'card'."""
    card = np.full((400, 600, 3), 220, dtype=np.uint8)
    # Light oval + dark eyes (rough frontal face for Haar)
    cv2 = pytest.importorskip("cv2")
    cv2.ellipse(card, (480, 120), (45, 60), 0, 0, 360, (180, 160, 140), -1)
    cv2.circle(card, (465, 110), 6, (40, 40, 40), -1)
    cv2.circle(card, (495, 110), 6, (40, 40, 40), -1)
    cv2.ellipse(card, (480, 140), (15, 8), 0, 0, 180, (60, 40, 40), 2)

    portrait = extract_portrait(card, detector_backend="opencv", padding=0.2)
    # Haar may or may not fire on synthetic blobs — if it does, crop must be smaller
    if portrait is not None:
        assert portrait.bgr.shape[0] < card.shape[0]
        assert portrait.bgr.shape[1] < card.shape[1]
        assert portrait.method in {"haar", "deepface"}


def test_corrupt_image_raises() -> None:
    # Must be ≥32 bytes after decode so we hit imdecode, not the size gate
    payload = b"not-a-valid-image-payload-xxxxxxxxxxxx"
    assert len(payload) >= 32
    with pytest.raises(FaceImageError) as ei:
        decode_base64_image(
            base64.b64encode(payload).decode(),
            max_bytes=1_000_000,
        )
    assert ei.value.code == "corrupt_image"
