import re
from parsers.utils import extract_raw_text


def parse(pdf_path, vendor):

    raw_text = extract_raw_text(pdf_path)

    # Normalize whitespace but keep structure
    normalized = re.sub(r'\s+', ' ', raw_text)

    invoice_number = ""
    purchase_order = ""
    total_amount = ""

    # =========================================================
    # 1️⃣ INVOICE NUMBER (Top Box)
    # =========================================================
    invoice_match = re.search(
        r"Invoice\s*No\.?\s*(\d{6})",
        normalized,
        re.IGNORECASE
    )

    if invoice_match:
        invoice_number = invoice_match.group(1)

    # Fallback if label split by OCR
    if not invoice_number:
        block_match = re.search(
            r"Invoice\s*No\.?\s*Date\s*(\d{6})",
            normalized,
            re.IGNORECASE
        )
        if block_match:
            invoice_number = block_match.group(1)

    # =========================================================
    # 2️⃣ Purchase Order (Extract from flattened table row)
    # Pattern: 0001181-0000 BIS-02 135562
    # =========================================================
    po_row_match = re.search(
        r"\b\d{7}-\d{4}\s+[A-Z0-9\-]+\s+(\d{5,8})\b",
        normalized
    )

    if po_row_match:
        purchase_order = po_row_match.group(1)

    # =========================================================
    # 3️⃣ TOTAL AMOUNT
    # =========================================================
    total_match = re.search(
        r"Total\s*\$?\s*([\d,]+\.\d{2})",
        normalized,
        re.IGNORECASE
    )

    if total_match:
        total_amount = total_match.group(1)

    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"
    }