import subprocess
import re

from extract_land import extract_land_record as extract_land_dlm
from extract_land_pdf import extract_land_record as extract_land_pdf


BENGALI_RE = re.compile(r'[\u0980-\u09FF]')


def is_banglarbhumi_pdf(pdf_path: str) -> bool:
    """
    True  -> BanglarBhumi Bengali PDF
    False -> English Plot PDF
    """

    try:
        result = subprocess.run(
            ["pdftotext", "-layout", pdf_path, "-"],
            capture_output=True,
            text=True,
            encoding="utf-8",
            timeout=10,
        )

        if result.returncode != 0:
            return False

        return bool(BENGALI_RE.search(result.stdout))

    except Exception:
        return False


def extract_land_record(pdf_path):
    """
    Automatically selects the correct extractor.
    """

    if is_banglarbhumi_pdf(pdf_path):
        print("✅ BanglarBhumi PDF detected")
        return extract_land_dlm(pdf_path)

    print("✅ English Plot PDF detected")
    return extract_land_pdf(pdf_path)