"""Synthetic sales report. Business logic only; no network or filesystem access."""

import csv
import io
import re


def sales_report(csv_text: str) -> str:
    """Return Markdown from at most 100 rows and 32 KiB of CSV text."""
    if not isinstance(csv_text, str) or len(csv_text) > 32768:
        raise ValueError("CSV must be text of at most 32 KiB")
    if len(csv_text.encode("utf-8")) > 32768:
        raise ValueError("CSV must be text of at most 32 KiB")
    reader = csv.DictReader(io.StringIO(csv_text), strict=True)
    try:
        fieldnames = reader.fieldnames
    except csv.Error as error:
        raise ValueError("Malformed CSV header") from error
    if fieldnames != ["product", "quantity", "unit_price_cents"]:
        raise ValueError("Expected product,quantity,unit_price_cents")
    lines = ["# Sales report", "", "| Product | Quantity | Amount (USD) |", "| --- | ---: | ---: |"]
    total = 0
    count = 0
    try:
        for count, row in enumerate(reader, 1):
            if count > 100 or set(row) != {"product", "quantity", "unit_price_cents"}:
                raise ValueError("Expected at most 100 rows with exactly three fields")
            product = row["product"] or ""
            if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9 ._-]{0,59}", product):
                raise ValueError("Product must contain 1–60 plain label characters")
            values = []
            for field, ceiling in [("quantity", 10000), ("unit_price_cents", 100000000)]:
                text = row[field] or ""
                if not re.fullmatch(r"[0-9]{1,9}", text) or not 1 <= int(text) <= ceiling:
                    raise ValueError(f"{field} must be an integer between 1 and {ceiling}")
                values.append(int(text))
            quantity, price = values
            amount = quantity * price
            total += amount
            lines.append(f"| {product} | {quantity} | {amount // 100}.{amount % 100:02d} |")
    except csv.Error as error:
        raise ValueError("Malformed CSV") from error
    if count == 0:
        raise ValueError("At least one sales row is required")
    return "\n".join([*lines, "", f"Total: USD {total // 100}.{total % 100:02d}", ""])
