"""Reproduce the article's synthetic sales calculations. Python 3, no packages."""
import csv
import json
import sys
from collections import Counter
from datetime import date
from decimal import Decimal
from pathlib import Path


def analyze(file):
    with Path(file).open(newline='', encoding='utf-8') as stream:
        raw = list(csv.DictReader(stream))
    unique = []
    seen = {}
    duplicates = []
    for row in raw:
        key = row['order_id']
        if key in seen:
            if seen[key] != row:
                raise ValueError('Conflicting order ID: ' + key)
            duplicates.append(key)
            continue
        seen[key] = row
        unique.append(row)
    completed = [r for r in unique if r['status'] == 'completed']
    monthly = {}
    channels = {}
    for row in completed:
        month = date.fromisoformat(row['order_date']).isoformat()[:7]
        if month not in ('2026-01', '2026-02'):
            raise ValueError('Unexpected month: ' + month)
        gross, refund = Decimal(row['gross_sales_usd']), Decimal(row['refund_usd'])
        if not gross.is_finite() or not refund.is_finite():
            raise ValueError('Non-finite amount')
        if gross < 0 or refund < 0 or refund > gross:
            raise ValueError('Invalid amount for ' + row['order_id'])
        totals = monthly.setdefault(month, {'gross': Decimal(0), 'refunds': Decimal(0), 'net': Decimal(0), 'orders': 0})
        totals['gross'] += gross
        totals['refunds'] += refund
        totals['net'] += gross - refund
        totals['orders'] += 1
        channel = channels.setdefault(row['channel'], {})
        channel[month] = channel.get(month, Decimal(0)) + gross - refund
    for month, totals in monthly.items():
        totals['net_aov'] = totals['net'] / totals['orders']
        totals['refund_rate_pct'] = totals['refunds'] / totals['gross'] * 100
        assert sum(v.get(month, Decimal(0)) for v in channels.values()) == totals['net']
    change = monthly['2026-02']['net'] - monthly['2026-01']['net']
    return {
        'raw_rows': len(raw), 'exact_duplicate_order_ids': duplicates,
        'unique_orders': len(unique), 'status_counts_after_deduplication': dict(Counter(r['status'] for r in unique)),
        'excluded_order_ids': [r['order_id'] for r in unique if r['status'] != 'completed'],
        'completed_orders': len(completed), 'monthly': monthly, 'channel_net_sales': channels,
        'net_sales_change_usd': change,
        'net_sales_change_pct': change / monthly['2026-01']['net'] * 100,
    }


if __name__ == '__main__':
    result = analyze(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).with_name('sales-example.csv'))
    print(json.dumps(result, indent=2, default=lambda x: str(x) if isinstance(x, Decimal) else x))
