import re
from parsers.utils import (
    extract_raw_text,
    extract_final_balance_due,
    extract_with_gemini
)

def parse(pdf_path, vendor):
    # -----------------------------------------
    # Initialize fields
    # -----------------------------------------
    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # -----------------------------------------
    # 1️⃣ Extract raw text
    # -----------------------------------------
    raw_text = extract_raw_text(pdf_path)

    # -----------------------------------------
    # 2️⃣ Extract Invoice Number
    # -----------------------------------------
    def extract_invoice_number(text):
        pattern = r"INVOICE\s*[:\-]?\s*(\d{3,})"
        match = re.search(pattern, text, re.IGNORECASE)
        return match.group(1) if match else ""

    invoice_number = extract_invoice_number(raw_text)

    # -----------------------------------------
    # 3️⃣ Extract Purchase Order
    # -----------------------------------------
    def extract_po(text):
        pattern = r"PURCHASE\s*ORDER\s*[:\-]?\s*([A-Z0-9\-]+)"
        match = re.search(pattern, text, re.IGNORECASE)
        return match.group(1) if match else ""

    purchase_order = extract_po(raw_text)

    # -----------------------------------------
    # 4️⃣ Extract Total Amount
    # -----------------------------------------
    total_amount = extract_final_balance_due(raw_text)

    # -----------------------------------------
    # 5️⃣ AI Fallback (Gemini)
    # -----------------------------------------
    try:
        if not (invoice_number and purchase_order and total_amount):
            ai_data = extract_with_gemini(raw_text)
            if isinstance(ai_data, dict):
                invoice_number = invoice_number or ai_data.get("invoice_number", "").strip()
                purchase_order = purchase_order or ai_data.get("purchase_order", "").strip()
               