"""OCR extraction from government ID images.

Production uses pytesseract when available. Tests inject FakeOCRProvider.
Never invents high-confidence fields — missing/low-confidence → inconclusive.
"""

from __future__ import annotations

import logging
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import date, datetime
from functools import lru_cache
from typing import Any

import cv2
import numpy as np

logger = logging.getLogger(__name__)

_DATE_PATTERNS = [
    re.compile(r"\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b"),  # YYYY-MM-DD
    re.compile(r"\b(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})\b"),  # DD-MM-YYYY or MM-DD-YYYY
    re.compile(
        r"\b(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+(\d{4})\b",
        re.I,
    ),
]
_MONTHS = {
    "jan": 1,
    "feb": 2,
    "mar": 3,
    "apr": 4,
    "may": 5,
    "jun": 6,
    "jul": 7,
    "aug": 8,
    "sep": 9,
    "oct": 10,
    "nov": 11,
    "dec": 12,
}
_ID_NUMBER_RE = re.compile(
    r"\b(?:ID|No\.?|Number|Passport|DL|License)[:\s#]*([A-Z0-9][-A-Z0-9]{4,20})\b",
    re.I,
)
_GENERIC_ID_RE = re.compile(r"\b([A-Z]{1,3}\d{6,12}|\d{9,12}[A-Z]?)\b")
_NAME_LABEL_RE = re.compile(
    r"(?:Name|Surname|Given Names?|Full Name)\s*[:\-]?\s*([A-Za-z][A-Za-z\s\-']{1,60})",
    re.I,
)
_DOC_KEYWORDS = {
    "passport": ("passport", "passeport"),
    "drivers_license": ("driver", "driving", "license", "licence", "dl "),
    "national_id": ("national id", "identity card", "citizen", "aadhaar", "nid"),
}


@dataclass
class OcrResult:
    full_name: str | None = None
    id_number: str | None = None
    date_of_birth: str | None = None
    expiry_date: str | None = None
    issue_date: str | None = None
    document_type: str | None = None
    nationality: str | None = None
    sex: str | None = None
    raw_text: str = ""
    confidence: float | None = None
    provider: str = "none"
    conclusive: bool = False
    warnings: list[str] = field(default_factory=list)
    error_code: str | None = None


class OCRProvider(ABC):
    name: str = "ocr"

    @abstractmethod
    def extract(
        self,
        bgr: np.ndarray,
        *,
        country: str | None = None,
        document_type_hint: str | None = None,
    ) -> OcrResult:
        ...


def _normalize_date(y: int, m: int, d: int) -> str | None:
    try:
        return date(y, m, d).isoformat()
    except ValueError:
        return None


def parse_dates_from_text(text: str) -> list[str]:
    found: list[str] = []
    for pat in _DATE_PATTERNS:
        for m in pat.finditer(text):
            g = m.groups()
            if len(g) == 3 and g[1].isalpha():
                mon = _MONTHS.get(g[1][:3].lower())
                if mon:
                    iso = _normalize_date(int(g[2]), mon, int(g[0]))
                    if iso:
                        found.append(iso)
                continue
            if len(g[0]) == 4:
                iso = _normalize_date(int(g[0]), int(g[1]), int(g[2]))
            else:
                # Ambiguous DMY vs MDY — prefer DMY when day > 12
                a, b, y = int(g[0]), int(g[1]), int(g[2])
                if a > 12:
                    iso = _normalize_date(y, b, a)
                elif b > 12:
                    iso = _normalize_date(y, a, b)
                else:
                    iso = _normalize_date(y, b, a)  # assume DMY
            if iso:
                found.append(iso)
    # unique preserve order
    out: list[str] = []
    for d in found:
        if d not in out:
            out.append(d)
    return out


def infer_document_type(text: str, hint: str | None = None) -> str:
    if hint:
        return hint.strip().lower().replace(" ", "_")
    lower = text.lower()
    for dtype, keys in _DOC_KEYWORDS.items():
        if any(k in lower for k in keys):
            return dtype
    return "government_id"


def parse_structured_fields(
    text: str,
    *,
    document_type_hint: str | None = None,
    min_confidence: float = 0.45,
    provider: str = "parser",
    ocr_confidence: float | None = None,
) -> OcrResult:
    warnings: list[str] = []
    if not text or len(text.strip()) < 8:
        return OcrResult(
            raw_text=text or "",
            confidence=ocr_confidence,
            provider=provider,
            conclusive=False,
            warnings=["OCR text empty or too short"],
            error_code="ocr_inconclusive",
        )

    name = None
    nm = _NAME_LABEL_RE.search(text)
    if nm:
        name = re.sub(r"\s+", " ", nm.group(1)).strip(" :-")
        # Drop trailing keywords accidentally captured
        for stop in ("Date", "DOB", "Sex", "Nationality", "Expires", "Valid"):
            if stop in name:
                name = name.split(stop)[0].strip()
    if not name:
        # Fallback: longest alphabetic line that looks like a person name
        candidates = []
        for line in text.splitlines():
            line = line.strip()
            if re.fullmatch(r"[A-Za-z][A-Za-z\s\-']{2,50}", line):
                if line.lower() not in {"passport", "identity", "driver license"}:
                    candidates.append(line)
        if candidates:
            name = max(candidates, key=len)

    id_number = None
    im = _ID_NUMBER_RE.search(text)
    if im:
        id_number = im.group(1).upper()
    else:
        gm = _GENERIC_ID_RE.search(text)
        if gm:
            id_number = gm.group(1).upper()

    dates = parse_dates_from_text(text)
    today = date.today().isoformat()
    expiry = None
    dob = None
    issue = None
    # Heuristic: expiry is future-most date; DOB is oldest past date far from today
    past = [d for d in dates if d < today]
    future = [d for d in dates if d >= today]
    if future:
        expiry = max(future)
    if past:
        past_sorted = sorted(past)
        dob = past_sorted[0]
        if len(past_sorted) > 1:
            issue = past_sorted[-1]

    # Label-assisted overrides
    for label, attr in (
        (r"(?:Date of Birth|DOB|Birth)\s*[:\-]?\s*", "dob"),
        (r"(?:Expiry|Expiration|Expires|Valid Until)\s*[:\-]?\s*", "expiry"),
        (r"(?:Issue|Issued)\s*[:\-]?\s*", "issue"),
    ):
        m = re.search(label + r"([0-9A-Za-z/\-\s]{6,20})", text, re.I)
        if m:
            parsed = parse_dates_from_text(m.group(1))
            if parsed:
                if attr == "dob":
                    dob = parsed[0]
                elif attr == "expiry":
                    expiry = parsed[0]
                else:
                    issue = parsed[0]

    dtype = infer_document_type(text, document_type_hint)
    conf = ocr_confidence
    if conf is None:
        conf = 0.55 if (name and id_number) else 0.35 if name or id_number else 0.15

    conclusive = bool(name) and conf >= min_confidence
    if not conclusive:
        warnings.append("OCR fields incomplete or low confidence")
        error = "ocr_inconclusive"
    else:
        error = None
    if not id_number:
        warnings.append("ID number not extracted")

    excerpt = text.strip().replace("\n", " ")
    if len(excerpt) > 240:
        excerpt = excerpt[:240] + "…"

    return OcrResult(
        full_name=name,
        id_number=id_number,
        date_of_birth=dob,
        expiry_date=expiry,
        issue_date=issue,
        document_type=dtype,
        raw_text=excerpt,
        confidence=round(conf, 4),
        provider=provider,
        conclusive=conclusive,
        warnings=warnings,
        error_code=error,
    )


class TesseractOCRProvider(OCRProvider):
    name = "tesseract"

    def extract(
        self,
        bgr: np.ndarray,
        *,
        country: str | None = None,
        document_type_hint: str | None = None,
    ) -> OcrResult:
        try:
            import pytesseract
            from pytesseract import Output
        except ImportError:
            return OcrResult(
                provider="tesseract",
                conclusive=False,
                warnings=["pytesseract not installed"],
                error_code="ocr_unavailable",
            )

        gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
        gray = cv2.bilateralFilter(gray, 9, 75, 75)
        _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        try:
            data: dict[str, Any] = pytesseract.image_to_data(
                thresh, output_type=Output.DICT
            )
            text = pytesseract.image_to_string(thresh)
        except Exception as exc:  # noqa: BLE001
            # Missing system tesseract binary, etc.
            logger.info("Tesseract OCR failed: %s", type(exc).__name__)
            return OcrResult(
                provider="tesseract",
                conclusive=False,
                warnings=[f"OCR engine error: {type(exc).__name__}"],
                error_code="ocr_unavailable",
            )

        confs = [
            float(c)
            for c in data.get("conf", [])
            if str(c) not in {"-1", ""} and float(c) >= 0
        ]
        mean_conf = (sum(confs) / len(confs) / 100.0) if confs else None
        return parse_structured_fields(
            text,
            document_type_hint=document_type_hint,
            provider=self.name,
            ocr_confidence=mean_conf,
        )


class HeuristicOCRProvider(OCRProvider):
    """Last-resort: OpenCV preprocess + empty parse (always inconclusive without text)."""

    name = "heuristic"

    def extract(
        self,
        bgr: np.ndarray,
        *,
        country: str | None = None,
        document_type_hint: str | None = None,
    ) -> OcrResult:
        return OcrResult(
            document_type=document_type_hint or "government_id",
            provider=self.name,
            conclusive=False,
            warnings=["No OCR engine available — extraction inconclusive"],
            error_code="ocr_unavailable",
        )


_ocr_override: OCRProvider | None = None


def set_ocr_provider_override(provider: OCRProvider | None) -> None:
    global _ocr_override
    _ocr_override = provider
    get_ocr_provider.cache_clear()


@lru_cache
def get_ocr_provider() -> OCRProvider:
    if _ocr_override is not None:
        return _ocr_override
    try:
        import pytesseract  # noqa: F401

        return TesseractOCRProvider()
    except ImportError:
        return HeuristicOCRProvider()


def expiry_is_valid(expiry_iso: str | None, *, today: date | None = None) -> bool | None:
    """True if unexpired, False if expired, None if unknown/unparseable."""
    if not expiry_iso:
        return None
    try:
        exp = date.fromisoformat(expiry_iso[:10])
    except ValueError:
        try:
            exp = datetime.fromisoformat(expiry_iso.replace("Z", "+00:00")).date()
        except ValueError:
            return None
    ref = today or date.today()
    return exp >= ref
