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
    # Strategy:
    # Find the "INVOICE #" label and capture
    # the LAST number near it (not phone numbers)
    # =========================================================
    lines = raw_text.splitlines()
    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
    # Strictly capture value after P.O. NUMBER
    # =========================================================
    for i, line in enumerate(lines):
        if "P.O. NUMBER" in line.upper():
            for j in range(1, 3):
                if i + j < len(lines):
                    candidate = lines[i + j].strip()
                    po_match = re.search(r"[A-Z0-9\-]+", candidate)
                    if po_match:
                        purchase_order = po_match.group(0)
                        break
            break

    # =========================================================
    # 3️⃣ Total Amount
    # Capture the LAST Total amount in document
    # =========================================================
    totals = re.findall(
        r"\bTotal\b\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"
    }