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 = ""

    # ---------------------------
    # Invoice Number
    # ---------------------------
    match = re.search(
        r"Invoice\s*#:\s*(\S+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        invoice_number = match.group(1)

    # ---------------------------
    # Purchase Order
    # ---------------------------
    match = re.search(
        r"Customer\s+Purchase\s+Order\s+#:\s*(\S+)",
        raw_text,
        re.IGNORECASE
    )
    if match:
        purchase_order = match.group(1)

    # ---------------------------
    # Final Total (take last match)
    # ---------------------------
    matches = re.findall(
        r"Invoice\s+Total\s+\(USD\)\s+([\d,]+\.\d+)",
        raw_text,
        re.IGNORECASE
    )

    if matches:
        total_amount = matches[-1]

    # Fallback (if layout 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"
    }