import re
from parsers.utils import extract_raw_text

def parse(pdf_path, vendor):
    raw_text = extract_raw_text(pdf_path)

    # Normalize text
    text = re.sub(r"\s+", " ", raw_text)

    # -----------------------------------------
    # 1️⃣ Account Number (acts as invoice_number)
    # -----------------------------------------
    invoice_number = ""
    account_match = re.search(
        r"Account\s*Number[:\s]*([\d\-]+)",
        text,
        re.IGNORECASE
    )
    if account_match:
        invoice_number = account_match.group(1)

    # -----------------------------------------
    # 2️⃣ Purchase Order (NOT PRESENT)
    # -----------------------------------------
    purchase_order = ""

    # -----------------------------------------
    # 3️⃣ Total Amount (Amount Due)
    # -----------------------------------------
    total_amount = ""

    # First match (top-right)
    amount_match = re.search(s
        r"Amount\s*Due[:\s]*\$?([\d,]+\.\d{2})",
        text,
        re.IGNORECASE
    )

    if amount_match:
        total_amount = amount_match.group(1).replace(",", "")
    else:
        # fallback (bottom payment slip)
        fallback_match = re.search(
            r"AMOUNT\s+DUE\s*\$?([\d,]+\.\d{2})",
            raw_text,
            re.IGNORECASE
        )
        if fallback_match:
            total_amount = fallback_match.group(1).replace(",", "")

    # -----------------------------------------
    # 4️⃣ AI Fallback (rarely needed here)
    # -----------------------------------------
    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", "")
                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,  # actually account number
        "purchase_order": purchase_order,  # always blank
        "total_amount_usd": f"${total_amount}" if total_amount else "",
        "status": "Processed" if invoice_number else "Pending"
    }