import re
from parsers.utils import extract_raw_text

def parse(pdf_path, vendor):
    raw_text = extract_raw_text(pdf_path)

    # Normalize text (VERY important for this PDF)
    text = re.sub(r"\s+", " ", raw_text)

    # -----------------------------------------
    # 1️⃣ Invoice Number (multi-line label)
    # -----------------------------------------
    invoice_number = ""
    invoice_match = re.search(
        r"Invoice Number:\s*([A-Z0-9\-]+)",
        raw_text,  # use raw_text to preserve line breaks
        re.IGNORECASE
    )
    if invoice_match:
        invoice_number = invoice_match.group(1).strip()

    # -----------------------------------------
    # 2️⃣ Purchase Order (P.O. No.)
    # -----------------------------------------
    purchase_order = ""
    po_match = re.search(
        r"P\.?O\.?\s*No\.?\s*[:\-]?\s*(PO\d+)",
        text,
        re.IGNORECASE
    )
    if po_match:
        purchase_order = po_match.group(1)

    # -----------------------------------------
    # 3️⃣ Total Amount (bottom total block)
    # -----------------------------------------
    total_amount = ""

    # Prefer "Total:" followed by value
    total_match = re.search(
        r"Total:\s*\$?([\d,]+\.\d{2})",
        text,
        re.IGNORECASE
    )

    if total_match:
        total_amount = total_match.group(1).replace(",", "")
    else:
        # fallback to Net Invoice if needed
        fallback_match = re.search(
            r"Net Invoice:\s*\$?([\d,]+\.\d{2})",
            text,
            re.IGNORECASE
        )
        if fallback_match:
            total_amount = fallback_match.group(1).replace(",", "")

    # -----------------------------------------
    # 4️⃣ AI Fallback (only if needed)
    # -----------------------------------------
    if not invoice_number or not total_amount:
        from parsers.utils import extract_with_gemini
        try:
            ai_data = extract_with_gemini(raw_text)
            if isinstance(ai_data, dict):
                invoice_number = invoice_number or ai_data.get("invoice_number", "")
                purchase_order = purchase_order or ai_data.get("purchase_order", "")
                total_amount = total_amount or ai_data.get("total_amount_usd", "").replace("$", "")
        except Exception:
            pass

    # -----------------------------------------
    # 5️⃣ Output
    # -----------------------------------------
    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"
    }