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
    # Match date + invoice row
    # Example:
    # 2/23/2026 42912
    # =========================
    match = re.search(
        r"\b\d{1,2}/\d{1,2}/\d{4}\s+(\d{4,8})\b",
        raw_text
    )
    if match:
        invoice_number = match.group(1)

    # =========================
    # 2️⃣ Purchase Order
    # Under P.O. Number label
    # =========================
    lines = raw_text.splitlines()

    for i, line in enumerate(lines):
        if "P.O. NUMBER" in line.upper():
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                po_match = re.search(r"PO[0-9\-]+", next_line)
                if po_match:
                    purchase_order = po_match.group(0)
            break

    # =========================
    # 3️⃣ Total Amount
    # Capture final Total (not Subtotal)
    # =========================
    totals = re.findall(
        r"Total\s*\$?\s*([\d,]+\.\d{2})",
        raw_text,
        re.IGNORECASE
    )

    if totals:
        total_amount = totals[-1]  # last occurrence only

    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"
    }