import re
import pdfplumber
import pytesseract
from pdf2image import convert_from_path


# IMPORTANT: Set this to your installed Tesseract path
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"


# ---------------------------------
# Extract raw text with OCR fallback
# ---------------------------------
def extract_raw_text(pdf_path):

    full_text = ""

    # 1️⃣ Try normal text extraction
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            if text:
                full_text += text + "\n"

    # 2️⃣ If empty → use OCR
    if not full_text.strip():

        images = convert_from_path(
        pdf_path,
        dpi=300,
        poppler_path="C:\\poppler\\Library\\bin"
)

        for img in images:
            ocr_text = pytesseract.image_to_string(img)
            full_text += ocr_text + "\n"

    return full_text


# ---------------------------------
# Main Parse Function
# ---------------------------------
def parse(pdf_path, vendor):

    raw_text = extract_raw_text(pdf_path)

    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # ---------------------------
    # Invoice Number
    # ---------------------------
    match = re.search(
        r"Invoice\s*number\s*[\r\n\s]+(\d+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        invoice_number = match.group(1)

    # ---------------------------
    # Purchase Order
    # ---------------------------
    match = re.search(
        r"Cust.*?order.*?(PO\d+)",
        raw_text,
        re.IGNORECASE | re.DOTALL
    )
    if match:
        purchase_order = match.group(1)

    # ---------------------------
    # Total Amount USD
    # ---------------------------
    matches = re.findall(
        r"\bTotal\b\s*([\d,]+\.\d{2})",
        raw_text,
        re.IGNORECASE
    )

    if matches:
        total_amount = matches[-1]

    return {
        "vendor_name": vendor,
        "invoice_number": invoice_number,
        "purchase_order": purchase_order,
        "total_amount_usd": f"${total_amount}" if total_amount else "",
        "status": "Processed" if invoice_number else "Pending"
    }