import re
from parsers.utils import (
    extract_raw_text,
    extract_with_gemini,
    extract_final_balance_due
)

def parse(pdf_path, vendor):
    """
    Accurate Pallet Repairing invoices often come in multi-invoice PDFs.
    This parser extracts ONLY the first invoice block.
    """

    # -----------------------------------------
    # Initialize fields
    # -----------------------------------------
    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # -----------------------------------------
    # 1️⃣ Extract raw text
    # -----------------------------------------
    raw_text = extract_raw_text(pdf_path)

    # Split into pages — Accurate Pallet uses clear page breaks
    pages = raw_text.split("Accurate Pallet Repairing")
    if len(pages) > 1:
        first_page = pages[1]  # first invoice block
    else:
        first_page = raw_text

    # -----------------------------------------
    # 2️⃣ Extract Invoice Number
    # -----------------------------------------
    def extract_invoice_number(text):
        # Matches: "Invoice # 15236/15253"
        pattern = r"Invoice\s*#?\s*[:\s]*([A-Za-z0-9\/\-]+)"
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            return match.group(1).strip()

        # Backup: ######/###### pattern
        pattern2 = r"\b[0-9]{4,6}\/[0-9]{4,6}\b"
        match2 = re.search(pattern2, text)
        if match2:
            return match2.group(0).strip()

        # Backup: single invoice number
        pattern3 = r"\b[0-9]{4,6}\b"
        match3 = re.search(pattern3, text)
        return match3.group(0).strip() if match3 else ""

    invoice_number = extract_invoice_number(first_page)

    # -----------------------------------------
    # 3️⃣ Extract Purchase Order Number
    # -----------------------------------------
    def extract_po(text):
        # Matches: "P.O. #" field
        pattern = r"P\.?O\.?\s*#?\s*[:\s]*([A-Za-z0-9\-]+)"
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            po = match.group(1).strip()
            # Ignore placeholders like blank or "Dave"
            if po.lower() not in ["", "none"]:
                return po
        return ""

    purchase_order = extract_po(first_page)

    # -----------------------------------------
    # 4️⃣ Extract Total Amount
    # -----------------------------------------
    # Accurate Pallet always shows:
    #   Total $1,580.00
    #   Balance Due $1,580.00
    total_amount = extract_final_balance_due(first_page)

    # -----------------------------------------
    # 5️⃣ AI fallback (Gemini)
    # -----------------------------------------
    try:
        if not invoice_number or not total_amount:
            ai_data = extract_with_gemini(first_page)
            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()
        )

    # -----------------------------------------
    # 7️⃣ Return consistent object
    # -----------------------------------------
    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"
    }