"""Document authenticity heuristics (quality + face-on-ID presence).

Not a forensic forgery detector — inconclusive results must not yield verified.
"""

from __future__ import annotations

from dataclasses import dataclass, field

import numpy as np

from app.config import get_settings
from app.services.face.image_ops import assess_image_quality
from app.services.id.ocr import OcrResult


@dataclass
class AuthenticityResult:
    passed: bool | None
    score: float | None
    face_on_id: bool | None
    quality_warnings: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    detail: str | None = None
    error_code: str | None = None


def _detect_face_on_id(bgr: np.ndarray) -> tuple[bool | None, float | None]:
    """Return (has_face, confidence-ish). Same portrait crop path as ArcFace."""
    settings = get_settings()
    try:
        from app.services.face.portrait import extract_portrait

        portrait = extract_portrait(
            bgr,
            detector_backend=settings.face_detector_backend,
            padding=float(settings.face_portrait_padding),
        )
    except Exception:  # noqa: BLE001
        return None, None
    if portrait is None:
        return False, 0.2
    # Prefer single face on ID portrait
    if portrait.face_count == 1:
        return True, 0.85 if portrait.method == "deepface" else 0.75
    if portrait.face_count > 1:
        return True, 0.55
    return True, 0.7


def assess_authenticity(
    bgr: np.ndarray,
    ocr: OcrResult,
    *,
    require_face_on_id: bool = True,
) -> AuthenticityResult:
    settings = get_settings()
    quality = assess_image_quality(
        bgr,
        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),
    )
    warnings: list[str] = list(quality)
    face_on_id, face_score = _detect_face_on_id(bgr)

    score_parts: list[float] = []
    # Quality
    if not quality:
        score_parts.append(0.9)
    elif len(quality) <= 1:
        score_parts.append(0.55)
        warnings.append("ID image quality marginal")
    else:
        score_parts.append(0.25)
        warnings.append("ID image quality failed authenticity heuristics")

    # OCR presence
    if ocr.conclusive:
        score_parts.append(0.85)
    elif ocr.full_name or ocr.id_number:
        score_parts.append(0.5)
    else:
        score_parts.append(0.2)
        warnings.append("Insufficient OCR evidence for authenticity")

    # Face portrait on document
    if face_on_id is True:
        score_parts.append(float(face_score or 0.7))
    elif face_on_id is False:
        score_parts.append(0.15)
        warnings.append("No face portrait detected on ID")
    else:
        score_parts.append(0.4)
        warnings.append("Face-on-ID detection inconclusive")

    # Expiry field present strengthens authenticity signal (not validity)
    if ocr.expiry_date:
        score_parts.append(0.8)
    else:
        score_parts.append(0.45)
        warnings.append("Expiry date not found on document")

    score = round(sum(score_parts) / len(score_parts), 4) if score_parts else None

    hard_fail = False
    inconclusive = False

    if len(quality) >= 2 and bool(settings.id_reject_on_quality_warnings):
        hard_fail = True
    if require_face_on_id and face_on_id is False:
        hard_fail = True
    if require_face_on_id and face_on_id is None:
        inconclusive = True
    if not ocr.conclusive and not (ocr.full_name or ocr.id_number):
        inconclusive = True
    if score is not None and score < 0.4:
        hard_fail = True
    elif score is not None and score < 0.55:
        inconclusive = True

    if hard_fail:
        return AuthenticityResult(
            passed=False,
            score=score,
            face_on_id=face_on_id,
            quality_warnings=quality,
            warnings=warnings,
            detail="Authenticity checks failed",
            error_code="authenticity_failed",
        )
    if inconclusive:
        return AuthenticityResult(
            passed=None,
            score=score,
            face_on_id=face_on_id,
            quality_warnings=quality,
            warnings=warnings,
            detail="Authenticity inconclusive — manual review required",
            error_code="authenticity_inconclusive",
        )
    return AuthenticityResult(
        passed=True,
        score=score,
        face_on_id=face_on_id,
        quality_warnings=quality,
        warnings=warnings,
        detail="Authenticity heuristics passed",
        error_code=None,
    )
