import re
from parsers.utils import extract_raw_text  # shared OCR utility


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\r\n]+(\d+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        invoice_number = match.group(1)

    # ---------------------------
    # Purchase Order (robust)
    # ---------------------------
    match = re.search(
        r"\bPO\s*0*\d+\b",
        raw_text,
        re.IGNORECASE
    )
    if match:
        purchase_order = match.group(0).replace(" ", "")

    # ---------------------------
    # Final Total (Amount Due)
    # ---------------------------
    matches = re.findall(
        r"AMOUNT\s+DUE[\s:\r\n]*([\d,]+\.\d{2})",
        raw_text,
        re.IGNORECASE
    )

    if matches:
        total_amount = matches[-1]

    # Fallback if label slightly changes
    if not total_amount:
        fallback_matches = re.findall(
            r"\bTotal\b.*?([\d,]+\.\d{2})",
            raw_text,
            re.IGNORECASE
        )
        if fallback_matches:
            total_amount = fallback_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"
    }