"""
BSS Skill: Invoice Parser
Extracts vendor, invoice number, date, line items, and totals from invoice text.
Outputs a compact structured representation for downstream validation and summarisation.
"""
import re

text = PROMPT  # noqa: F821

# ── Vendor ────────────────────────────────────────────────────────────────────
vendor_match = re.search(
    r"(?:from|vendor|company|billed? (?:from|by)|seller)[:\s]+([^\n]{3,60})",
    text, re.IGNORECASE,
)
vendor = vendor_match.group(1).strip() if vendor_match else "Unknown"

# ── Invoice number ────────────────────────────────────────────────────────────
# Match "INVOICE #ID" on a dedicated line; require the ID to contain a digit
inv_match = re.search(
    r"(?m)^[^\S\n]*invoice\s*#?\s*([A-Z0-9][A-Z0-9\-]*\d[A-Z0-9\-]*)",
    text, re.IGNORECASE,
)
inv_number = inv_match.group(1) if inv_match else "N/A"

# ── Date ──────────────────────────────────────────────────────────────────────
date_match = re.search(
    r"\b(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}"
    r"|\d{4}[/\-]\d{2}[/\-]\d{2}"
    r"|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\s+\d{1,2},?\s+\d{4})\b",
    text, re.IGNORECASE,
)
invoice_date = date_match.group(0) if date_match else "N/A"

# ── Line items ────────────────────────────────────────────────────────────────
amount_lines = []
for line in text.splitlines():
    if re.search(r"[\$€£¥]\s*[\d,]+\.?\d*|[\d,]+\.?\d*\s*(?:USD|EUR|GBP|usd|eur|€|\$)", line):
        cleaned = line.strip()
        # Exclude summary lines (subtotal, VAT, tax, total) — keep only true line items
        if (cleaned and len(cleaned) < 120 and
                not re.search(r'\b(?:sub\s*total|vat|tax|balance|total\s+due|grand\s+total|amount\s+due)\b',
                               cleaned, re.IGNORECASE)):
            amount_lines.append(cleaned)

# ── Total ─────────────────────────────────────────────────────────────────────
# Use \btotal\b to avoid matching "Subtotal"; prefer "total due" / "grand total"
total_match = re.search(
    r"(?:grand\s+total|amount\s+due|balance\s+due|total\s+due|\btotal\b)[:\s]+[\$€£¥]?\s*([\d,]+\.?\d*)",
    text, re.IGNORECASE,
)
total = total_match.group(1).replace(",", "") if total_match else "N/A"

# ── Currency ──────────────────────────────────────────────────────────────────
currency_match = re.search(r"(USD|EUR|GBP|JPY|CHF|\$|€|£|¥)", text)
currency = currency_match.group(1) if currency_match else ""

# ── Output ────────────────────────────────────────────────────────────────────
# Keep user instructions (anything before the first financial line)
first_financial = next((i for i, l in enumerate(text.splitlines())
                        if re.search(r"[\$€£¥]|invoice|bill", l, re.IGNORECASE)), 0)
instructions = " ".join(text.splitlines()[:first_financial])[:150].strip()

print(f"INVOICE:{inv_number} | DATE:{invoice_date} | VENDOR:{vendor} | CURRENCY:{currency}")
print(f"TOTAL:{total}")
print(f"LINE_ITEMS:{len(amount_lines)}")
for line in amount_lines[:15]:
    print(f"  {line}")
if instructions:
    print(f"CONTEXT:{instructions}")
