"""Xinzhi AI Lab: deterministic synthetic order audit, Python standard library only."""
import csv
import json
import sys
from decimal import Decimal, InvalidOperation
from pathlib import Path


def audit(path):
    totals = {'east': Decimal('0'), 'west': Decimal('0')}
    trace = []
    with Path(path).open(encoding='utf-8', newline='') as source:
        reader = csv.DictReader(source)
        required = {'order_id', 'region', 'quantity', 'unit_price'}
        if not required.issubset(reader.fieldnames or []):
            raise ValueError('Missing CSV columns')
        seen = set()
        for line, row in enumerate(reader, 2):
            reason = None
            order_id = (row.get('order_id') or '').strip()
            region = (row.get('region') or '').strip()
            if not order_id:
                reason = 'missing_order_id'
            elif order_id in seen:
                reason = 'duplicate_order_id'
            elif region not in totals:
                reason = 'unsupported_region'
            try:
                quantity = Decimal(row.get('quantity') or '')
                price = Decimal(row.get('unit_price') or '')
                if not quantity.is_finite() or not price.is_finite():
                    reason = reason or 'non_finite_number'
                elif quantity <= 0 or quantity != quantity.to_integral_value():
                    reason = reason or 'quantity_must_be_positive_integer'
                elif price < 0 or price != price.quantize(Decimal('0.01')):
                    reason = reason or 'price_must_be_nonnegative_cents'
            except (InvalidOperation, ValueError):
                reason = reason or 'invalid_number'
            record = {'line': line, 'order_id': order_id, 'included': reason is None}
            if reason:
                record['reason'] = reason
            else:
                seen.add(order_id)
                amount = quantity * price
                totals[region] += amount
                record['amount'] = format(amount, '.2f')
            trace.append(record)
    included = sum(row['included'] for row in trace)
    return {'rows': len(trace), 'included': included, 'excluded': len(trace) - included,
            'totals': {key: format(value, '.2f') for key, value in totals.items()}, 'trace': trace}


if __name__ == '__main__':
    path = sys.argv[1] if len(sys.argv) > 1 else Path(__file__).with_name('orders.csv')
    print(json.dumps(audit(path), ensure_ascii=False, indent=2))
