import re
from parsers.utils import (
    extract_raw_text,
    extract_final_balance_due,
    extract_with_gemini
)


def parse(pdf_path, vendor):

    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # =========================================
    # 1️⃣ Extract raw text
    # =========================================
    raw_text = extract_raw_text(pdf_path)

    # =========================================
    # 2️⃣ Deterministic Invoice Number
    # =========================================
    match = re.search(
        r"Invoice\s*#\s*(\d{5,})",
        raw_text,
        re.IGNORECASE
    )

    if match:
        invoice_number = match.group(1)

    # =========================================
    # 3️⃣ Deterministic PO Extraction
    # =========================================
    block_match = re.search(
        r"Account\s*#.*?Sales\s*Rep",
        raw_text,
        re.IGNORECASE | re.DOTALL
    )

    if block_match:
        block_text = block_match.group(0)

        numbers = re.findall(r"(?:\d[\s]*){6,12}", block_text)

        cleaned_numbers = []

        for n in numbers:
            cleaned = re.sub(r"\s+", "", n)

            if cleaned.isdigit() and len(cleaned) >= 6:
                if cleaned != invoice_number:
                    cleaned_numbers.append(cleaned)

        if cleaned_numbers:
            purchase_order = cleaned_numbers[-1]

    # =========================================
    # 4️⃣ Deterministic Final Balance Due
    # =========================================
    total_amount = extract_final_balance_due(raw_text)

    # =========================================
    # 5️⃣ AI Fallback (SAFE — INSIDE FUNCTION)
    # =========================================
    try:
        if not invoice_number or not purchase_order or not total_amount:

            ai_data = extract_with_gemini(raw_text)

            if isinstance(ai_data, dict):

                if not invoice_number:
                    invoice_number = ai_data.get("invoice_number", "").strip()

                if not purchase_order:
                    purchase_order = ai_data.get("purchase_order", "").strip()

                if not total_amount:
                    total_amount = ai_data.get("total_amount_usd", "").replace("$", "").strip()

    except Exception:
        pass

    # =========================================
    # 6️⃣ Final Sanitization
    # =========================================
    total_amount = total_amount.replace(",", "")

    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"
    }