import re
from parsers.utils import extract_raw_text

def parse(pdf_path, vendor):
    raw_text = extract_raw_text(pdf_path)

    # Split into invoice blocks
    blocks = re.split(r"INVOICE/CREDIT NO\.", raw_text)

    results = []

    for block in blocks[1:]:  # skip first split chunk
        text = re.sub(r"\s+", " ", block)

        # -----------------------------------------
        # 1️⃣ Invoice Number
        # -----------------------------------------
        invoice_number = ""
        inv_match = re.search(r"(\d{6,})", text)
        if inv_match:
            invoice_number = inv_match.group(1)

        # -----------------------------------------
        # 2️⃣ Purchase Order (GPO format)
        # -----------------------------------------
        purchase_order = ""
        po_match = re.search(
            r"(GPO\d+)",
            text,
            re.IGNORECASE
        )
        if po_match:
            purchase_order = po_match.group(1)

        # -----------------------------------------
        # 3️⃣ Total Amount
        # -----------------------------------------
        total_amount = ""
        total_match = re.search(
            r"INVOICE\s+TOTAL\s*\$?\s*([\d,]+\.\d{2})",
            text,
            re.IGNORECASE
        )
        if total_match:
            total_amount = total_match.group(1).replace(",", "")

        # Skip empty blocks
        if not invoice_number:
            continue

        results.append({
            "vendor_name": vendor,
            "invoice_number": invoice_number,
            "purchase_order": purchase_order,
            "total_amount_usd": f"${total_amount}" if total_amount else "",
            "status": "Processed"
        })

    return results