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):
        # Matches: "INVOICE NO. MI-171020"
        pattern = r"INVOICE\s*NO\.?\s*[:\-]?\s*([A-Za-z0-9\-]+)"
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            return match.group(1).strip()

        # Backup: MI-###### pattern
        pattern2 = r"\bMI-[0-9]{5,}\b"
        match2 = re.search(pattern2, text)
        return match2.group(0).strip() if match2 else ""

    invoice_number = extract_invoice_number(raw_text)

    # -----------------------------------------
    # 3️⃣ Extract Purchase Order Number
    # -----------------------------------------
    def extract_po(text):
        # Matches: "PURCHASE ORDER NUMBER WRSEC03515"
        pattern = r"PURCHASE\s*ORDER\s*NUMBER\s*[:\-]?\s*([A-Za-z0-9\-]+)"
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            return match.group(1).strip()

        # Backup: WRSEC##### style
        pattern2 = r"\bWRSEC[0-9]{4,6}\b"
        match2 = re.search(pattern2, text)
        return match2.group(0).strip() if match2 else ""

    purchase_order = extract_po(raw_text)

    # -----------------------------------------
    # 4️⃣ Extract Total Amount
    # -----------------------------------------
    # Invoice shows:
    #   TOTAL AMOUNT DUE $173.60
    #   SUB TOTAL $173.60
    total_amount = extract_final_balance_due(raw_text)

    # -----------------------------------------
    # 5️⃣ AI fallback (Gemini)
    # -----------------------------------------
    try:
        if not (invoice_number 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()
                total_amount = (
                    total_amount
                    or ai_data.get("total_amount_usd", "").replace("$", "").strip()
                )
    except Exception:
        pass

    # -----------------------------------------
    # 6️⃣ Final sanitization
    # -----------------------------------------
    if total_amount:
        total_amount = (
            total_amount.replace(",", "")
            .replace("$", "")
            .strip()
        )

    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"
    }