import re
from parsers.utils import extract_raw_text


def parse(pdf_path, vendor):

    raw_text = extract_raw_text(pdf_path)
    normalized = re.sub(r'\s+', ' ', raw_text)

    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # =========================================================
    # 1️⃣ Invoice Number
    # =========================================================
    invoice_match = re.search(
        r"INVOICE\s*#\s*(\d+)",
        normalized,
        re.IGNORECASE
    )

    if invoice_match:
        invoice_number = invoice_match.group(1)

    # =========================================================
    # 2️⃣ Purchase Order (Optional – only if exists)
    # This invoice does not show one clearly,
    # so we safely attempt detection.
    # =========================================================
    po_match = re.search(
        r"\bPO\d+\b",
        normalized,
        re.IGNORECASE
    )

    if po_match:
        purchase_order = po_match.group(0)

    # =========================================================
    # 3️⃣ Total Amount
    # =========================================================
    total_match = re.search(
        r"\bTOTAL\s+([\d,]+\.\d{2})",
        normalized,
        re.IGNORECASE
    )

    if total_match:
        total_amount = total_match.group(1)

    # Fallback: Balance Due
    if not total_amount:
        balance_match = re.search(
            r"BALANCE\s+DUE\s*\$?\s*([\d,]+\.\d{2})",
            normalized,
            re.IGNORECASE
        )
        if balance_match:
            total_amount = balance_match.group(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"
    }