"""Small, fail-fast CSV import example. Python 3.10+, standard library only."""
import csv
import re
from decimal import Decimal

FIELDS = ("id", "email", "amount", "status")
EMAIL = re.compile(r"[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63}", re.ASCII)
AMOUNT = re.compile(r"[0-9]{1,12}(?:\.[0-9]{1,2})?", re.ASCII)


def bounded_lines(stream, max_chars, max_line_chars):
    """Bound decoded characters, including physical line terminators."""
    used = 0
    while True:
        line = stream.readline(max_line_chars + 1)
        if not line:
            return
        used += len(line)
        if len(line) > max_line_chars:
            raise ValueError("Physical line exceeds character limit")
        if used > max_chars:
            raise ValueError("Input exceeds total character limit")
        yield line


def iter_records(stream, *, max_rows=10_000, max_chars=16_777_216,
                 max_line_chars=65_536):
    """Yield validated rows; fail on the first error without retaining history.

    The caller owns the text stream. These are character bounds, not an HTTP
    upload-byte limit. Apply byte and time limits before decoding network input.
    """
    if min(max_rows, max_chars, max_line_chars) < 1:
        raise ValueError("Limits must be positive")
    reader = csv.reader(bounded_lines(stream, max_chars, max_line_chars), strict=True)
    try:
        header = next(reader, None)
        if header is None:
            raise ValueError("Missing header")
        header = [cell.strip() for cell in header]
        if len(header) != len(set(header)):
            raise ValueError("Duplicate header")
        if len(header) != len(FIELDS) or set(header) != set(FIELDS):
            raise ValueError("Header must contain exactly id,email,amount,status")
        for number, cells in enumerate(reader, 1):
            if number > max_rows:
                raise ValueError("Row limit exceeded")
            if len(cells) != len(header):
                raise ValueError(f"Record {number}: wrong column count")
            row = dict(zip(header, (cell.strip() for cell in cells)))
            if not re.fullmatch(r"[0-9]{1,18}", row["id"], flags=re.ASCII):
                raise ValueError(f"Record {number}: invalid id")
            if len(row["email"]) > 254 or not EMAIL.fullmatch(row["email"]):
                raise ValueError(f"Record {number}: unsupported email format")
            if not AMOUNT.fullmatch(row["amount"]):
                raise ValueError(f"Record {number}: invalid amount")
            if row["status"] not in {"active", "pending", "suspended"}:
                raise ValueError(f"Record {number}: invalid status")
            yield {"id": int(row["id"]), "email": row["email"],
                   "amount": Decimal(row["amount"]), "status": row["status"]}
    except csv.Error as exc:
        raise ValueError(f"CSV parsing failed near physical line {reader.line_num}") from exc


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path")
    args = parser.parse_args()
    # This parser setting is process-wide; set once in this standalone CLI.
    csv.field_size_limit(65_536)
    try:
        with open(args.path, encoding="utf-8-sig", newline="") as source:
            count = sum(1 for _ in iter_records(source))
    except (ValueError, UnicodeError, OSError) as exc:
        parser.exit(1, f"Rejected: {exc}\n")
    print(f"Validated {count} records; no database writes performed.")
