"""Reconstruct multiple-record allocation types from the public Olist ZIP.
Usage: python analysis.py /path/to/olist.zip
Source: https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce
Payment rows are allocations, not proof of duplicate charges or amounts currently due.
"""
import csv,io,zipfile,sys
from pathlib import Path
from collections import defaultdict,Counter

def analyze(archive):
 orders=defaultdict(list)
 with zipfile.ZipFile(archive) as z:
  name=next(x for x in z.namelist() if x.endswith('olist_order_payments_dataset.csv'))
  with z.open(name) as f:
   for r in csv.DictReader(io.TextIOWrapper(f,encoding='utf-8-sig')):orders[r['order_id']].append(r['payment_type'])
 multiple=[v for v in orders.values() if len(v)>1];groups=Counter(tuple(sorted(set(v))) for v in multiple)
 assert groups=={('credit_card','voucher'):2245,('credit_card',):287,('voucher',):427,('credit_card','debit_card'):1,('debit_card',):1}
 results={'orders':len(orders),'payment_rows':sum(len(v) for v in orders.values()),'multiple_record_orders':len(multiple),'mixed_method_orders':sum(n for g,n in groups.items() if len(g)>1),'same_method_orders':sum(n for g,n in groups.items() if len(g)==1),'voucher_only_multiple':groups[('voucher',)],'card_only_multiple':groups[('credit_card',)],'debit_only_multiple':groups[('debit_card',)]}
 results['extra_rows']=results['payment_rows']-results['orders'];results['row_order_overstatement_pct']=results['extra_rows']/results['orders']*100;results['voucher_only_share_of_voucher_multi_pct']=427/2672*100
 return results
if __name__=='__main__':
 results=analyze(sys.argv[1]);p=Path(__file__).parent/'data';p.mkdir(exist_ok=True)
 with (p/'allocation-decomposition.csv').open('w',newline='') as f:
  w=csv.writer(f);w.writerow(['metric','value']);w.writerows(results.items())
 print(results)
