"""Reproduce delivered-order identity and first-review cohorts from Olist's public archive."""
from collections import Counter, defaultdict
import csv
from datetime import datetime, timedelta
from io import TextIOWrapper
import json
import sys
from zipfile import ZipFile


START=datetime(2018,1,1)
END=datetime(2018,5,1)
WINDOWS=(30,60,90)


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


def outcome(counts, first, later):
    counts['eligible']+=1
    if later is not None:
        for days in WINDOWS:
            counts[f'day_{days}']+=later<=first+timedelta(days=days)


def analyze(path):
    by_customer=defaultdict(list)
    review=defaultdict(list)
    order_ids=Counter()
    with ZipFile(path) as book:
        customers={r['customer_id']:(r['customer_unique_id'],r['customer_state']) for r in records(book,'customers')}
        for r in records(book,'orders'):
            if r['order_status']!='delivered':
                continue
            customer=r['customer_id']
            stable,state=customers[customer]
            order_ids[customer]+=1
            purchase=datetime.fromisoformat(r['order_purchase_timestamp'])
            delivery=datetime.fromisoformat(r['order_delivered_customer_date']) if r['order_delivered_customer_date'] else None
            by_customer[stable].append((purchase,r['order_id'],state,delivery))
        for r in records(book,'order_reviews'):
            reviewed=datetime.fromisoformat(r['review_answer_timestamp'])
            review[r['order_id']].append((reviewed,r['review_id'],int(r['review_score'])))
    assert sum(order_ids.values())==96478 and len(by_customer)==93358
    cohorts=defaultdict(Counter)
    reviews=defaultdict(Counter)
    for orders in by_customer.values():
        orders.sort()
        (first,order,state,delivery),*later_orders=orders
        later=later_orders[0][0] if later_orders else None
        if START<=first<END:
            outcome(cohorts['All'],first,later)
            outcome(cohorts[state],first,later)
        if delivery is None:
            continue
        candidates=[item for item in review[order] if delivery<=item[0]<=delivery+timedelta(days=14)]
        if not candidates:
            continue
        answer,_,score=min(candidates)
        if not START<=answer<END or (later is not None and later<=answer):
            continue
        band='1–2' if score<=2 else '3' if score==3 else '4–5'
        outcome(reviews[band],answer,later)
    return {'identity':{'orders':sum(order_ids.values()),'order_customer_ids':len(order_ids),
                        'stable_ids':len(by_customer),'repeat_order_ids':sum(n>1 for n in order_ids.values()),
                        'repeat_stable_ids':sum(len(v)>1 for v in by_customer.values())},
            'first_observed':dict(cohorts),'first_review':dict(reviews)}


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