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*No\.?\s*(\d+)",
        normalized,
        re.IGNORECASE
    )

    if invoice_match:
        invoice_number = invoice_match.group(1)

    # =========================================================
    # 2️⃣ Purchase Order (Your Order)
    # =========================================================
    po_match = re.search(
        r"Your\s*Order\s*(PO\d+)",
        normalized,
        re.IGNORECASE
    )

    if po_match:
        purchase_order = po_match.group(1)

    # =========================================================
    # 3️⃣ Total Amount
    # Allow line breaks between label and value
    # =========================================================
    total_match = re.search(
        r"Invoice\s*Total\s*\$?\s*([\d,]+\.\d{2})",
        normalized,
        re.IGNORECASE
    )

    if total_match:
        total_amount = total_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"
    }