import re
from parsers.utils import extract_raw_text


def parse(pdf_path, vendor):

    raw_text = extract_raw_text(pdf_path)

    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # ---------------------------------------------------
    # Normalize text to avoid layout issues
    # ---------------------------------------------------
    normalized_text = re.sub(r'\s+', ' ', raw_text)

    # -----------------------------------------
    # Invoice Number (Actek Texas Robust Mode)
    # -----------------------------------------

    # Find all 6–8 digit standalone numbers
    candidates = re.findall(r"\b\d{6,8}\b", raw_text)

    for num in candidates:
        # Skip PO numbers (already handled separately)
        if num.startswith("20"):  # skip potential dates like 20260223
            continue

        # Skip Sales Order (4009803 appears too)
        if num == "4009803":
            continue

        invoice_number = num
        break

    # ---------------------------------------------------
    # Purchase Order
    # ---------------------------------------------------
    match = re.search(r"\bPO\d+\b", normalized_text)
    if match:
        purchase_order = match.group(0)

    # ---------------------------------------------------
    # Final Total Only
    # ---------------------------------------------------
    totals = re.findall(
        r"\(USD\)\s*Total\s*\$?([\d,]+\.\d{2})",
        normalized_text,
        re.IGNORECASE
    )
    if totals:
        total_amount = totals[-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"
    }