from __future__ import annotations

from pathlib import Path

import pdfplumber

from .models import PageAnalysis, PdfAnalysis

VIETNAMESE_ACCENTS = set(
    "áàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệíìỉĩị"
    "óòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđ"
)
MOJIBAKE_HINTS = ("~", "<)", "VI~T", "Tl}", "duQ", "cLla", "�")


def _page_stats(page_number: int, text: str, image_count: int) -> PageAnalysis:
    alpha_chars = sum(1 for char in text if char.isalpha())
    accents = sum(1 for char in text.lower() if char in VIETNAMESE_ACCENTS)
    mojibake_hits = sum(text.count(token) for token in MOJIBAKE_HINTS)
    return PageAnalysis(
        page=page_number,
        text_chars=len(text),
        alpha_chars=alpha_chars,
        accent_ratio=round(accents / max(alpha_chars, 1), 4),
        mojibake_hits=mojibake_hits,
        image_count=image_count,
    )


def analyze_pdf(path: Path) -> PdfAnalysis:
    path = Path(path)
    pages: list[PageAnalysis] = []
    with pdfplumber.open(str(path)) as pdf:
        for index, page in enumerate(pdf.pages, start=1):
            text = page.extract_text() or ""
            pages.append(_page_stats(index, text, len(page.images)))

    page_count = len(pages)
    text_chars = sum(page.text_chars for page in pages)
    image_pages = sum(1 for page in pages if page.image_count > 0)
    has_text_layer = text_chars >= max(120, page_count * 30)
    scan_likelihood = "high" if image_pages >= max(1, page_count // 2) and not has_text_layer else "low"
    recommended_route = "digital_text" if has_text_layer and scan_likelihood == "low" else "local_ocr"
    warnings: list[str] = []
    if recommended_route == "local_ocr":
        warnings.append("scan_pdf_requires_ocr")

    return PdfAnalysis(
        input_path=str(path),
        page_count=page_count,
        file_size_mb=round(path.stat().st_size / 1024 / 1024, 2),
        pages=pages,
        has_text_layer=has_text_layer,
        scan_likelihood=scan_likelihood,
        recommended_route=recommended_route,
        warnings=warnings,
    )

