"""Government ID verification — OCR, authenticity, face match, liveness, consent."""

from __future__ import annotations

import asyncio
import base64
import logging
import re
from datetime import timedelta

import httpx

from app.config import get_settings
from app.schemas.common import JobStatus
from app.schemas.face_verification import FaceFrameResult
from app.schemas.id_verification import (
    IdCheckResult,
    IdExtractedData,
    IdVerificationRequest,
    IdVerificationResponse,
    IdVerificationStatus,
)
from app.services.face.engine import FaceEngineResult, get_face_engine
from app.services.face.image_ops import FaceImageError, decode_base64_image
from app.services.id.authenticity import assess_authenticity
from app.services.id.crypto_store import id_crypto_store
from app.services.id.ocr import expiry_is_valid, get_ocr_provider
from app.services.id.status_store import (
    IdVerificationRecord,
    id_status_store,
    mask_id_number,
    new_verification_id,
)
from app.services.face.audit_store import _iso, _utc_now

logger = logging.getLogger(__name__)


def _normalize_name(value: str | None) -> str:
    if not value:
        return ""
    cleaned = re.sub(r"[^a-zA-Z\s\-']", " ", value.lower())
    return re.sub(r"\s+", " ", cleaned).strip()


def _names_match(expected: str | None, extracted: str | None) -> tuple[bool | None, float | None]:
    """Return (matched, score). None matched = inconclusive."""
    if not expected:
        return None, None
    if not extracted:
        return None, 0.0
    a = _normalize_name(expected)
    b = _normalize_name(extracted)
    if not a or not b:
        return None, 0.0
    if a == b:
        return True, 1.0
    a_parts = set(a.split())
    b_parts = set(b.split())
    if not a_parts or not b_parts:
        return None, 0.0
    overlap = len(a_parts & b_parts) / max(len(a_parts), len(b_parts))
    # Containment (OCR often returns surname + given in different order)
    if a in b or b in a:
        return True, max(0.85, overlap)
    if overlap >= 0.67:
        return True, round(overlap, 4)
    if overlap >= 0.4:
        return None, round(overlap, 4)  # inconclusive
    return False, round(overlap, 4)


def _decide_status(
    *,
    consent_ok: bool,
    ocr_conclusive: bool,
    expiry_valid: bool | None,
    authenticity_passed: bool | None,
    name_matched: bool | None,
    expected_name: str | None,
    identity_matched: bool | None,
    liveness_passed: bool | None,
    live_frames_present: bool,
    hard_error: str | None,
) -> tuple[IdVerificationStatus, str | None]:
    """Never return verified unless every required check is conclusively true."""
    if hard_error in {
        "consent_required",
        "invalid_image",
        "image_too_large",
        "corrupt_image",
        "max_attempts_exceeded",
    }:
        return IdVerificationStatus.REJECTED, hard_error

    rejects: list[str] = []
    inconclusive: list[str] = []

    if not consent_ok:
        rejects.append("consent_required")

    if expiry_valid is False:
        rejects.append("id_expired")
    elif expiry_valid is None:
        inconclusive.append("expiry_unknown")

    if authenticity_passed is False:
        rejects.append("authenticity_failed")
    elif authenticity_passed is None:
        inconclusive.append("authenticity_inconclusive")

    if not ocr_conclusive:
        inconclusive.append("ocr_inconclusive")

    if expected_name:
        if name_matched is False:
            rejects.append("name_mismatch")
        elif name_matched is None:
            inconclusive.append("name_inconclusive")

    if not live_frames_present:
        inconclusive.append("live_capture_missing")
    else:
        if liveness_passed is False:
            rejects.append("liveness_failed")
        elif liveness_passed is None:
            inconclusive.append("liveness_inconclusive")
        if identity_matched is False:
            rejects.append("identity_mismatch")
        elif identity_matched is None:
            inconclusive.append("identity_inconclusive")

    if hard_error and hard_error not in rejects and hard_error not in inconclusive:
        # Treat unknown hard errors as reject unless marked soft
        if hard_error.endswith("_inconclusive") or hard_error in {
            "ocr_unavailable",
            "engine_error",
            "insufficient_frames",
        }:
            inconclusive.append(hard_error)
        else:
            rejects.append(hard_error)

    if rejects:
        return IdVerificationStatus.REJECTED, rejects[0]
    if inconclusive:
        return IdVerificationStatus.MANUAL_REVIEW, inconclusive[0]

    # All required checks conclusively passed
    required_ok = (
        consent_ok
        and ocr_conclusive
        and authenticity_passed is True
        and expiry_valid is True
        and live_frames_present
        and liveness_passed is True
        and identity_matched is True
        and (name_matched is True if expected_name else True)
    )
    if required_ok:
        return IdVerificationStatus.VERIFIED, None
    return IdVerificationStatus.MANUAL_REVIEW, "checks_incomplete"


class IdVerificationService:
    async def verify(self, payload: IdVerificationRequest) -> IdVerificationResponse:
        settings = get_settings()
        max_attempts = int(settings.id_max_attempts)
        interview_key = payload.interview_id or f"anon-{payload.candidate_id or 'unknown'}"
        attempt = id_status_store.attempt_count(payload.interview_id or interview_key) + 1
        attempts_remaining = max(0, max_attempts - attempt)
        retry_allowed = attempt < max_attempts
        verification_id = new_verification_id()
        warnings: list[str] = []
        checks: list[IdCheckResult] = []

        if attempt > max_attempts:
            return await self._finalize(
                payload,
                verification_id=verification_id,
                attempt=attempt,
                attempts_remaining=0,
                retry_allowed=False,
                consent_ok=False,
                checks=[
                    IdCheckResult(
                        name="attempts",
                        passed=False,
                        detail="Maximum ID verification attempts exceeded",
                    )
                ],
                warnings=["Maximum ID verification attempts exceeded"],
                hard_error="max_attempts_exceeded",
                ocr_conclusive=False,
                expiry_valid=None,
                authenticity_passed=False,
                name_matched=None,
                identity_matched=None,
                liveness_passed=None,
                live_frames_present=False,
            )

        # --- Consent ---
        consent_ok = bool(payload.consent_given)
        checks.append(
            IdCheckResult(
                name="consent",
                passed=consent_ok,
                detail=(
                    f"consent_id={payload.consent_id}"
                    if consent_ok
                    else "consent_given must be true"
                ),
            )
        )
        if not consent_ok:
            warnings.append("Consent required before ID verification can succeed")

        # --- Decode ID image ---
        try:
            id_b64 = payload.id_image_base64
            if payload.id_source_url and not id_b64:
                raw = await self._fetch_url(payload.id_source_url)
                id_b64 = base64.b64encode(raw).decode("ascii")
            max_bytes = int(settings.id_max_image_bytes)
            id_decoded = decode_base64_image(id_b64 or "", max_bytes=max_bytes)
        except FaceImageError as exc:
            warnings.append(str(exc))
            return await self._finalize(
                payload,
                verification_id=verification_id,
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                consent_ok=consent_ok,
                checks=checks
                + [
                    IdCheckResult(
                        name="id_image", passed=False, detail=str(exc)
                    )
                ],
                warnings=warnings,
                hard_error=exc.code,
                ocr_conclusive=False,
                expiry_valid=None,
                authenticity_passed=False,
                name_matched=None,
                identity_matched=None,
                liveness_passed=None,
                live_frames_present=False,
            )
        except Exception as exc:  # noqa: BLE001
            logger.exception("ID image fetch/decode failed")
            return await self._finalize(
                payload,
                verification_id=verification_id,
                attempt=attempt,
                attempts_remaining=attempts_remaining,
                retry_allowed=retry_allowed,
                consent_ok=consent_ok,
                checks=checks
                + [
                    IdCheckResult(
                        name="id_image",
                        passed=False,
                        detail=f"Image load failed: {type(exc).__name__}",
                    )
                ],
                warnings=warnings + [f"Image load failed: {type(exc).__name__}"],
                hard_error="invalid_image",
                ocr_conclusive=False,
                expiry_valid=None,
                authenticity_passed=False,
                name_matched=None,
                identity_matched=None,
                liveness_passed=None,
                live_frames_present=False,
            )

        checks.append(
            IdCheckResult(
                name="id_image",
                passed=True,
                detail=f"{id_decoded.width}x{id_decoded.height}",
            )
        )

        # --- Encrypted storage ---
        encrypted_storage_id = None
        raw_bytes: bytes | None = None
        try:
            # Re-decode original bytes for storage
            raw_b64 = (payload.id_image_base64 or id_b64 or "").strip()
            if "," in raw_b64 and raw_b64.lower().startswith("data:"):
                raw_b64 = raw_b64.split(",", 1)[1]
            raw_bytes = base64.b64decode(raw_b64, validate=False)
        except Exception:  # noqa: BLE001
            raw_bytes = None
        if payload.store_encrypted_image and raw_bytes:
            try:
                meta = await asyncio.to_thread(
                    id_crypto_store.store,
                    raw_bytes,
                    interview_id=payload.interview_id,
                )
                encrypted_storage_id = meta.storage_id
            except Exception as exc:  # noqa: BLE001
                logger.warning("Encrypted ID storage failed: %s", type(exc).__name__)
                warnings.append("Encrypted storage failed — continuing without persist")

        # --- OCR ---
        ocr_provider = get_ocr_provider()
        ocr = await asyncio.to_thread(
            ocr_provider.extract,
            id_decoded.bgr,
            country=payload.id_country,
            document_type_hint=payload.document_type_hint,
        )
        warnings.extend(ocr.warnings)
        checks.append(
            IdCheckResult(
                name="ocr",
                passed=True if ocr.conclusive else None,
                score=ocr.confidence,
                detail=ocr.error_code or "ok",
            )
        )

        # --- Expiry ---
        exp_valid = expiry_is_valid(ocr.expiry_date)
        checks.append(
            IdCheckResult(
                name="expiry",
                passed=exp_valid,
                detail=ocr.expiry_date or "not_found",
            )
        )
        if exp_valid is False:
            warnings.append(f"Document expired ({ocr.expiry_date})")

        # --- Authenticity ---
        auth = await asyncio.to_thread(
            assess_authenticity,
            id_decoded.bgr,
            ocr,
            require_face_on_id=bool(settings.id_require_face_on_document),
        )
        warnings.extend(auth.warnings)
        checks.append(
            IdCheckResult(
                name="authenticity",
                passed=auth.passed,
                score=auth.score,
                detail=auth.detail,
            )
        )

        # --- Name match ---
        name_matched, name_score = _names_match(payload.expected_name, ocr.full_name)
        checks.append(
            IdCheckResult(
                name="name_match",
                passed=name_matched,
                score=name_score,
                detail=(
                    f"expected={payload.expected_name!r} extracted={ocr.full_name!r}"
                    if payload.expected_name
                    else "expected_name not provided"
                ),
            )
        )

        # Optional DOB check
        if payload.expected_date_of_birth and ocr.date_of_birth:
            dob_ok = payload.expected_date_of_birth[:10] == ocr.date_of_birth[:10]
            checks.append(
                IdCheckResult(
                    name="dob_match",
                    passed=dob_ok,
                    detail=f"expected={payload.expected_date_of_birth} extracted={ocr.date_of_birth}",
                )
            )
            if not dob_ok:
                warnings.append("Date of birth mismatch")
                # Treat as hard reject signal via name path? use authenticity? add to hard
                # We'll fold into name_matched failure if DOB provided
                if name_matched is True:
                    name_matched = False

        # --- Live frames + face engine ---
        live_list = list(payload.live_frames_base64 or [])
        if payload.live_image_base64:
            live_list.append(payload.live_image_base64)

        identity_matched: bool | None = None
        liveness_passed: bool | None = None
        face_match_score: float | None = None
        face_distance: float | None = None
        face_threshold: float | None = None
        liveness_score: float | None = None
        face_model: str | None = None
        frame_results: list[FaceFrameResult] = []
        live_frames_present = bool(live_list)
        hard_error: str | None = None

        if live_list:
            try:
                live_decoded = [
                    decode_base64_image(b64, max_bytes=max_bytes) for b64 in live_list
                ]
                min_frames = int(settings.face_min_live_frames)
                if len(live_decoded) < min_frames:
                    warnings.append(
                        f"Need at least {min_frames} live frame(s); got {len(live_decoded)}"
                    )
                    hard_error = "insufficient_frames"
                    live_frames_present = False
                    checks.append(
                        IdCheckResult(
                            name="live_frames",
                            passed=False,
                            detail=f"got {len(live_decoded)} need {min_frames}",
                        )
                    )
                else:
                    max_frames = int(settings.face_max_live_frames)
                    if len(live_decoded) > max_frames:
                        live_decoded = live_decoded[:max_frames]
                    checks.append(
                        IdCheckResult(
                            name="live_frames",
                            passed=True,
                            detail=f"{len(live_decoded)} frame(s)",
                        )
                    )
                    engine = get_face_engine()
                    try:
                        result: FaceEngineResult = await asyncio.to_thread(
                            engine.analyze,
                            registered_bgr=id_decoded.bgr,
                            live_frames_bgr=[d.bgr for d in live_decoded],
                        )
                    except Exception as exc:  # noqa: BLE001
                        logger.exception("Face engine failed during ID verify")
                        hard_error = "engine_error"
                        warnings.append(f"Face analysis failed: {type(exc).__name__}")
                        result = None  # type: ignore[assignment]

                    if result is not None:
                        identity_matched = result.identity_matched
                        liveness_passed = bool(result.liveness_passed)
                        face_match_score = result.match_score
                        face_distance = result.distance
                        face_threshold = result.threshold
                        liveness_score = result.liveness_score
                        face_model = result.model
                        frame_results = [
                            FaceFrameResult(
                                face_count=fr.face_count,
                                is_real=fr.is_real,
                                antispoof_score=fr.antispoof_score,
                                quality_warnings=fr.quality_warnings,
                                error=fr.error,
                            )
                            for fr in result.frame_results
                        ]
                        warnings.extend(result.warnings)
                        # Match without ArcFace metrics is inconclusive — never verify
                        if identity_matched is True and (
                            face_distance is None or face_threshold is None
                        ):
                            identity_matched = None
                            warnings.append(
                                "Identity match inconclusive — face distance/threshold missing"
                            )
                        if result.error_code and not (
                            identity_matched is True and liveness_passed
                        ):
                            hard_error = hard_error or result.error_code
                        checks.append(
                            IdCheckResult(
                                name="liveness",
                                passed=liveness_passed,
                                score=liveness_score,
                                detail=result.error_code if not liveness_passed else "ok",
                            )
                        )
                        checks.append(
                            IdCheckResult(
                                name="face_match",
                                passed=identity_matched,
                                score=face_match_score,
                                detail=(
                                    f"distance={face_distance} threshold={face_threshold}"
                                ),
                            )
                        )
            except FaceImageError as exc:
                warnings.append(str(exc))
                hard_error = exc.code
                live_frames_present = False
                checks.append(
                    IdCheckResult(name="live_frames", passed=False, detail=str(exc))
                )
        else:
            checks.append(
                IdCheckResult(
                    name="live_frames",
                    passed=None,
                    detail="No live frames — face match and liveness inconclusive",
                )
            )
            checks.append(
                IdCheckResult(name="liveness", passed=None, detail="skipped")
            )
            checks.append(
                IdCheckResult(name="face_match", passed=None, detail="skipped")
            )

        return await self._finalize(
            payload,
            verification_id=verification_id,
            attempt=attempt,
            attempts_remaining=attempts_remaining,
            retry_allowed=retry_allowed,
            consent_ok=consent_ok,
            checks=checks,
            warnings=warnings,
            hard_error=hard_error,
            ocr_conclusive=bool(ocr.conclusive),
            expiry_valid=exp_valid,
            authenticity_passed=auth.passed,
            name_matched=name_matched,
            identity_matched=identity_matched,
            liveness_passed=liveness_passed,
            live_frames_present=live_frames_present,
            ocr=ocr,
            face_match_score=face_match_score,
            face_distance=face_distance,
            face_threshold=face_threshold,
            liveness_score=liveness_score,
            face_model=face_model,
            frame_results=frame_results,
            encrypted_storage_id=encrypted_storage_id,
            id_image_sha256=id_decoded.content_sha256,
            name_score=name_score,
        )

    async def _finalize(
        self,
        payload: IdVerificationRequest,
        *,
        verification_id: str,
        attempt: int,
        attempts_remaining: int,
        retry_allowed: bool,
        consent_ok: bool,
        checks: list[IdCheckResult],
        warnings: list[str],
        hard_error: str | None,
        ocr_conclusive: bool,
        expiry_valid: bool | None,
        authenticity_passed: bool | None,
        name_matched: bool | None,
        identity_matched: bool | None,
        liveness_passed: bool | None,
        live_frames_present: bool,
        ocr=None,
        face_match_score: float | None = None,
        face_distance: float | None = None,
        face_threshold: float | None = None,
        liveness_score: float | None = None,
        face_model: str | None = None,
        frame_results: list[FaceFrameResult] | None = None,
        encrypted_storage_id: str | None = None,
        id_image_sha256: str | None = None,
        name_score: float | None = None,
    ) -> IdVerificationResponse:
        settings = get_settings()
        vstatus, error_code = _decide_status(
            consent_ok=consent_ok,
            ocr_conclusive=ocr_conclusive,
            expiry_valid=expiry_valid,
            authenticity_passed=authenticity_passed,
            name_matched=name_matched,
            expected_name=payload.expected_name,
            identity_matched=identity_matched,
            liveness_passed=liveness_passed,
            live_frames_present=live_frames_present,
            hard_error=hard_error,
        )
        # Absolute rule: never verified unless status says so — and never when
        # face match / liveness evidence is missing or inconclusive.
        verified = vstatus == IdVerificationStatus.VERIFIED
        face_evidence_ok = (
            identity_matched is True
            and face_distance is not None
            and face_threshold is not None
            and liveness_passed is True
            and liveness_score is not None
        )
        if verified and (
            not consent_ok
            or not ocr_conclusive
            or authenticity_passed is not True
            or expiry_valid is not True
            or not live_frames_present
            or not face_evidence_ok
            or (payload.expected_name and name_matched is not True)
        ):
            verified = False
            vstatus = IdVerificationStatus.MANUAL_REVIEW
            error_code = error_code or (
                "face_evidence_incomplete"
                if identity_matched is True and not face_evidence_ok
                else "checks_incomplete"
            )

        now = _utc_now()
        ttl = float(settings.id_verification_ttl_seconds)
        expires = now + timedelta(seconds=ttl) if verified else None

        extracted = None
        extracted_name = None
        extracted_id = None
        document_type = None
        if ocr is not None:
            extracted = IdExtractedData(
                full_name=ocr.full_name,
                id_number=mask_id_number(ocr.id_number),
                date_of_birth=ocr.date_of_birth,
                expiry_date=ocr.expiry_date,
                issue_date=ocr.issue_date,
                document_type=ocr.document_type,
                nationality=ocr.nationality,
                sex=ocr.sex,
                raw_text_excerpt=ocr.raw_text,
                ocr_confidence=ocr.confidence,
                ocr_provider=ocr.provider,
            )
            extracted_name = ocr.full_name
            extracted_id = mask_id_number(ocr.id_number)
            document_type = ocr.document_type

        # Overall match_score: prefer face; else name score; else 0.0 for API compat
        match_score = face_match_score
        if match_score is None and name_score is not None:
            match_score = name_score
        if match_score is None:
            match_score = 0.0

        interview_key = payload.interview_id or f"anon-{payload.candidate_id or 'unknown'}"
        record = IdVerificationRecord(
            verification_id=verification_id,
            interview_id=payload.interview_id or interview_key,
            candidate_id=payload.candidate_id,
            verification_status=vstatus.value,
            verified=verified,
            consent_given=consent_ok,
            consent_id=payload.consent_id,
            consent_version=payload.consent_version,
            consent_timestamp=payload.consent_timestamp,
            extracted_name=extracted_name,
            extracted_id_number_masked=extracted_id,
            document_type=document_type,
            match_score=match_score,
            identity_matched=identity_matched,
            liveness_passed=liveness_passed,
            expiry_valid=expiry_valid,
            authenticity_passed=authenticity_passed,
            name_matched=name_matched,
            encrypted_storage_id=encrypted_storage_id,
            id_image_sha256=id_image_sha256,
            attempt=attempt,
            error_code=None if verified else error_code,
            warnings=list(warnings),
            checks=[c.model_dump() for c in checks],
            created_at=_iso(now),
            verified_at=_iso(now) if verified else None,
            expires_at=_iso(expires) if expires else None,
        )
        id_status_store.save(record)

        job_status = (
            JobStatus.SUCCEEDED
            if vstatus != IdVerificationStatus.REJECTED
            else JobStatus.FAILED
        )
        # manual_review still "succeeded" as a completed analysis with non-verified outcome
        if vstatus == IdVerificationStatus.MANUAL_REVIEW:
            job_status = JobStatus.SUCCEEDED

        message = {
            IdVerificationStatus.VERIFIED: "ID verification passed",
            IdVerificationStatus.MANUAL_REVIEW: (
                f"ID verification requires manual review ({error_code or 'inconclusive'})"
            ),
            IdVerificationStatus.REJECTED: (
                f"ID verification rejected ({error_code or 'checks_failed'})"
            ),
        }[vstatus]

        return IdVerificationResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            candidate_id=payload.candidate_id,
            verification_id=verification_id,
            status=job_status,
            stub=False,
            message=message,
            verification_status=vstatus,
            verified=verified,
            extracted=extracted,
            extracted_name=extracted_name,
            extracted_id_number=extracted_id,
            document_type=document_type or "government_id",
            match_score=match_score,
            identity_matched=identity_matched,
            liveness_passed=liveness_passed,
            face_match_score=face_match_score,
            face_distance=face_distance,
            face_threshold=face_threshold,
            liveness_score=liveness_score,
            face_model=face_model,
            frame_results=frame_results or [],
            checks=checks,
            expiry_valid=expiry_valid,
            authenticity_passed=authenticity_passed,
            name_matched=name_matched,
            consent_recorded=consent_ok,
            encrypted_storage_id=encrypted_storage_id,
            id_image_sha256=id_image_sha256,
            attempt=attempt,
            attempts_remaining=attempts_remaining,
            retry_allowed=(not verified) and retry_allowed,
            verified_at=_iso(now) if verified else None,
            expires_at=_iso(expires) if expires else None,
            error_code=None if verified else error_code,
            warnings=warnings,
        )

    async def _fetch_url(self, url: str) -> bytes:
        async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
            res = await client.get(url)
            res.raise_for_status()
            return res.content
