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 = ""

    # =========================
    # 1️⃣ Invoice Number
    # Format: Invoice Q273772
    # =========================
    match = re.search(
        r"Invoice\s+([A-Z0-9\-]+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        invoice_number = match.group(1)

    # =========================
    # 2️⃣ Purchase Order
    # Under "Purchase Order No."
    # =========================
    match = re.search(
        r"Purchase\s+Order\s+No\.\s+.*?\n([A-Z0-9\-]+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        purchase_order = match.group(1)

    # =========================
    # 3️⃣ Total Amount
    # Capture LAST Total in document
    # =========================
    totals = re.findall(
        r"Total\s*\$?\s*([\d,]+\.\d{2})",
        raw_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"
    }