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 = ""

    lines = raw_text.splitlines()

    # =========================
    # 1️⃣ Invoice Number
    # Get value under "INVOICE No."
    # =========================
    for i, line in enumerate(lines):
        if "INVOICE NO" in line.upper():
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                match = re.search(r"\b\d{4,8}\b", next_line)
                if match:
                    invoice_number = match.group(0)
            break

    # =========================
    # 2️⃣ Purchase Order
    # Under PO# column
    # =========================
    match = re.search(
        r"\bPO\s*#\s*(\d+)",
        raw_text,
        re.IGNORECASE
    )

    if match:
        purchase_order = match.group(1)
    # =========================
    # 3️⃣ Total Amount
    # Capture largest numeric amount in document
    # (Safer than matching first Total)
    # =========================
    amounts = re.findall(r"\b\d+\.\d{2}\b", raw_text)

    if amounts:
        # Choose highest value (final invoice total)
        total_amount = max(amounts, key=lambda x: float(x))

    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"
    }