"""Reproduce Olist delivery-error tails and order-approval status cross-tabs."""
from collections import Counter, defaultdict
import csv
from datetime import datetime
from io import TextIOWrapper
import json
from statistics import median
import sys
from zipfile import ZipFile

FIRST=datetime(2017,1,1)
END=datetime(2018,8,1)


def records(book, table):
    with book.open(f'olist_{table}_dataset.csv') as stream:
        yield from csv.DictReader(TextIOWrapper(stream,encoding='utf-8-sig'))


def audit(path):
    states=defaultdict(list)
    approvals=defaultdict(Counter)
    with ZipFile(path) as book:
        customers={r['customer_id']:r['customer_state'] for r in records(book,'customers')}
        for row in records(book,'orders'):
            purchased=datetime.fromisoformat(row['order_purchase_timestamp'])
            if not FIRST<=purchased<END:
                continue
            status=row['order_status']
            approvals['present' if row['order_approved_at'] else 'blank'][status]+=1
            actual=row['order_delivered_customer_date']
            promised=row['order_estimated_delivery_date']
            if status=='delivered' and actual and promised:
                days=(datetime.fromisoformat(actual).date()-datetime.fromisoformat(promised).date()).days
                states[customers[row['customer_id']]].append(days)
                states['All'].append(days)
    def describe(values):
        return {'eligible':len(values),'late':sum(x>0 for x in values),
                'late_4_plus':sum(x>=4 for x in values),'late_8_plus':sum(x>=8 for x in values),
                'early_4_plus':sum(x<=-4 for x in values),'early_8_plus':sum(x<=-8 for x in values),
                'on_time_to_7_early':sum(-7<=x<=0 for x in values),'median_error':median(values)}
    return {'delivery_error':{key:describe(values) for key,values in states.items()},
            'approval_status':{key:{'orders':sum(counts.values()),'statuses':dict(counts)}
                               for key,counts in approvals.items()}}


if __name__=='__main__':
    print(json.dumps(audit(sys.argv[1]),indent=2))
