"""Extract a face portrait crop from ID documents (or any photo).

Government IDs place a small face on a large card. Passing the full card to
DeepFace with ``enforce_detection=True`` often fails even when a Haar/soft
detector finds the portrait. Cropping first makes ArcFace matching reliable.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass

import cv2
import numpy as np

logger = logging.getLogger(__name__)


@dataclass
class PortraitCrop:
    bgr: np.ndarray
    method: str  # haar | deepface | full
    face_count: int
    bbox: tuple[int, int, int, int] | None  # x, y, w, h in source coords


def _clamp_bbox(
    x: int, y: int, w: int, h: int, *, img_w: int, img_h: int, padding: float
) -> tuple[int, int, int, int]:
    pad_x = int(w * padding)
    pad_y = int(h * padding)
    x1 = max(0, x - pad_x)
    y1 = max(0, y - pad_y)
    x2 = min(img_w, x + w + pad_x)
    y2 = min(img_h, y + h + pad_y)
    return x1, y1, max(1, x2 - x1), max(1, y2 - y1)


def _haar_faces(bgr: np.ndarray) -> list[tuple[int, int, int, int]]:
    gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
    cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    cascade = cv2.CascadeClassifier(cascade_path)
    if cascade.empty():
        return []
    # ID portraits are often small relative to the card — allow tiny faces
    detected = cascade.detectMultiScale(
        gray,
        scaleFactor=1.08,
        minNeighbors=3,
        minSize=(24, 24),
        flags=cv2.CASCADE_SCALE_IMAGE,
    )
    return [(int(x), int(y), int(w), int(h)) for (x, y, w, h) in detected]


def _deepface_faces(bgr: np.ndarray, *, detector_backend: str) -> list[tuple[int, int, int, int]]:
    try:
        from app.services.face.lazy_deepface import get_deepface

        DeepFace = get_deepface()
        extracted = DeepFace.extract_faces(
            img_path=bgr,
            detector_backend=detector_backend,
            enforce_detection=False,
            align=False,
            anti_spoofing=False,
        )
    except Exception as exc:  # noqa: BLE001
        logger.info("DeepFace portrait extract failed: %s", type(exc).__name__)
        return []

    boxes: list[tuple[int, int, int, int]] = []
    for item in extracted or []:
        if not isinstance(item, dict):
            continue
        area = item.get("facial_area") or {}
        if not isinstance(area, dict):
            continue
        try:
            x = int(area.get("x", 0))
            y = int(area.get("y", 0))
            w = int(area.get("w") or area.get("width") or 0)
            h = int(area.get("h") or area.get("height") or 0)
        except (TypeError, ValueError):
            continue
        conf = item.get("confidence")
        try:
            conf_f = float(conf) if conf is not None else 1.0
        except (TypeError, ValueError):
            conf_f = 1.0
        # Soft extract can return full-frame ghosts — require a real box + confidence
        if w < 16 or h < 16:
            continue
        if conf_f < 0.5 and not (area.get("x") is not None and area.get("y") is not None):
            continue
        # Reject near-full-frame "faces" (detector fallback when nothing found)
        ih, iw = bgr.shape[:2]
        if w * h > 0.85 * iw * ih:
            continue
        boxes.append((x, y, w, h))
    return boxes


def _largest(boxes: list[tuple[int, int, int, int]]) -> tuple[int, int, int, int] | None:
    if not boxes:
        return None
    return max(boxes, key=lambda b: b[2] * b[3])


def _upscale_if_small(crop: np.ndarray, *, min_side: int = 112) -> np.ndarray:
    h, w = crop.shape[:2]
    side = min(h, w)
    if side >= min_side:
        return crop
    scale = min_side / float(side)
    new_w = max(min_side, int(round(w * scale)))
    new_h = max(min_side, int(round(h * scale)))
    return cv2.resize(crop, (new_w, new_h), interpolation=cv2.INTER_CUBIC)


def extract_portrait(
    bgr: np.ndarray,
    *,
    detector_backend: str = "opencv",
    padding: float = 0.35,
    min_side: int = 112,
) -> PortraitCrop | None:
    """Crop the primary face from ``bgr``. Returns None if no face found."""
    if bgr is None or bgr.size == 0:
        return None
    ih, iw = bgr.shape[:2]
    if ih < 8 or iw < 8:
        return None

    haar = _haar_faces(bgr)
    box = _largest(haar)
    method = "haar"
    face_count = len(haar)

    if box is None:
        df_boxes = _deepface_faces(bgr, detector_backend=detector_backend)
        box = _largest(df_boxes)
        method = "deepface"
        face_count = len(df_boxes)

    if box is None:
        return None

    x, y, w, h = box
    x, y, w, h = _clamp_bbox(x, y, w, h, img_w=iw, img_h=ih, padding=padding)
    crop = bgr[y : y + h, x : x + w].copy()
    if crop.size == 0:
        return None
    crop = _upscale_if_small(crop, min_side=min_side)
    return PortraitCrop(
        bgr=crop,
        method=method,
        face_count=face_count,
        bbox=(x, y, w, h),
    )


def frames_mean_abs_diff(a: np.ndarray, b: np.ndarray) -> float:
    """Mean absolute pixel difference after resizing ``b`` to ``a``'s shape."""
    if a.shape != b.shape:
        b = cv2.resize(b, (a.shape[1], a.shape[0]), interpolation=cv2.INTER_AREA)
    return float(np.mean(np.abs(a.astype(np.float32) - b.astype(np.float32))))


def live_frames_are_static_replay(
    frames: list[np.ndarray],
    *,
    min_mean_abs_diff: float,
) -> bool:
    """True when every consecutive pair is nearly identical (same still photo)."""
    if len(frames) < 2:
        return False
    for i in range(1, len(frames)):
        if frames_mean_abs_diff(frames[i - 1], frames[i]) >= min_mean_abs_diff:
            return False
    return True


def live_matches_reference_too_closely(
    reference_bgr: np.ndarray,
    live_frames: list[np.ndarray],
    *,
    min_mean_abs_diff: float,
) -> bool:
    """True when any live frame is nearly a pixel copy of the reference (print/replay)."""
    for frame in live_frames:
        if frames_mean_abs_diff(reference_bgr, frame) < min_mean_abs_diff:
            return True
    return False
