"""
BSS Skill: Line Validator
Validates invoice line items produced by invoice-parser.
Checks that line amounts sum to the declared total; flags duplicate amounts,
suspiciously round numbers, and missing totals.
"""
import re

text = PROMPT  # noqa: F821

lines = text.splitlines()
total_declared = None
line_amounts = []
flags = []

# ── Parse invoice-parser output ───────────────────────────────────────────────
in_items = False
for line in lines:
    stripped = line.strip()
    if stripped.startswith("TOTAL:"):
        raw = stripped.split(":", 1)[1].strip().split("|")[0].strip()
        try:
            total_declared = float(raw.replace(",", ""))
        except ValueError:
            pass
        in_items = False
    elif stripped.startswith("LINE_ITEMS:"):
        in_items = True
    elif in_items and line.startswith("  "):
        # Extract complete currency amounts; lookahead prevents partial matches and unit rates
        amounts = re.findall(r"[\$€£¥]\s*([\d,]+(?:\.\d+)?)(?=[^\d/]|$)", stripped)
        for a in amounts:
            try:
                v = float(a.replace(",", ""))
                if 0.01 < v < 10_000_000:
                    line_amounts.append(v)
            except ValueError:
                pass

# ── Validations ───────────────────────────────────────────────────────────────
if total_declared is None:
    flags.append("MISSING_TOTAL: no declared total found")
elif not line_amounts:
    flags.append("NO_LINE_AMOUNTS: could not extract individual amounts")
else:
    subtotal = sum(line_amounts)
    diff = abs(subtotal - total_declared)
    if diff > max(0.02 * total_declared, 0.01):
        flags.append(
            f"TOTAL_MISMATCH: declared={total_declared:.2f} "
            f"sum={subtotal:.2f} diff={diff:.2f}"
        )

# Duplicate amounts (potential double-billing)
seen: dict = {}
for amt in line_amounts:
    seen[amt] = seen.get(amt, 0) + 1
for amt, cnt in seen.items():
    if cnt > 1 and amt > 10:
        flags.append(f"DUPLICATE_AMOUNT:{amt:.2f} appears {cnt}x")

# Suspiciously round large amounts
for amt in line_amounts:
    if amt >= 1000 and amt % 100 == 0:
        flags.append(f"ROUND_AMOUNT:{amt:.0f} — verify correctness")
        break  # flag once

# ── Output (pass through + append validation block) ───────────────────────────
print(text)
print(f"VALIDATION:{'PASS' if not flags else 'WARNINGS'}")
for f in flags[:5]:
    print(f"  FLAG:{f}")
if not flags and total_declared is not None:
    print(f"  OK:total {total_declared:.2f} validated")
