"""Synthetic reporting demo. Run: python monthly-report.py monthly-sales.csv
Writes report.csv beside the input. No dependencies beyond Python 3.
Duplicate IDs and invalid records fail validation; nothing is silently removed.
"""
import csv
import sys
from collections import defaultdict
from datetime import date
from decimal import Decimal, InvalidOperation
from pathlib import Path


def summarize(path):
    totals = defaultdict(lambda: Decimal('0'))
    seen = set()
    with Path(path).open(newline='', encoding='utf-8-sig') as source:
        reader = csv.DictReader(source)
        required = {'order_id', 'order_date', 'region', 'amount'}
        if set(reader.fieldnames or []) != required:
            raise ValueError('Expected order_id, order_date, region, amount columns')
        for line, row in enumerate(reader, 2):
            if any(value is None for value in row.values()) or None in row:
                raise ValueError(f'Line {line}: malformed CSV row')
            key = row['order_id'].strip()
            region = row['region'].strip()
            if not key or not region or key in seen:
                raise ValueError(f'Line {line}: missing ID/region or duplicate order ID')
            date.fromisoformat(row['order_date'].strip())
            try:
                amount = Decimal(row['amount'].strip())
            except InvalidOperation as error:
                raise ValueError(f'Line {line}: invalid amount') from error
            if not amount.is_finite() or amount < 0 or amount != amount.quantize(Decimal('0.01')):
                raise ValueError(f'Line {line}: expected nonnegative amount with at most two decimals')
            seen.add(key)
            totals[region] += amount
    if not seen:
        raise ValueError('Input has no orders')
    return len(seen), dict(sorted(totals.items()))


if __name__ == '__main__':
    path = Path(sys.argv[1] if len(sys.argv) > 1 else 'monthly-sales.csv')
    count, totals = summarize(path)
    with path.with_name('report.csv').open('w', newline='', encoding='utf-8') as output:
        writer = csv.writer(output)
        writer.writerow(['region', 'total_amount'])
        writer.writerows((region, f'{amount:.2f}') for region, amount in totals.items())
    print(f'{count} orders; total {sum(totals.values()):.2f}; wrote report.csv')
