"""Reproduce aggregate sensitivity tests from the UCI Online Retail workbook.

Run: python retail_cohort_sensitivity.py online-retail.zip
Keep repeat-purchase-analysis.py beside this script. Requires Python 3.9 or later.
Only group totals and sorted aggregate contributions leave this process.
"""
from collections import Counter, defaultdict
from decimal import Decimal
from hashlib import sha256
from io import BytesIO
import json
from pathlib import Path
import re
from runpy import run_path
import sys
from zipfile import ZipFile

PRODUCT = re.compile(r'\d{5}[A-Z]*', re.I)


def summarize(path, reader):
    source=run_path(str(reader),run_name='workbook_reader')
    positive=defaultdict(lambda: defaultdict(Decimal))
    canceled=defaultdict(lambda: defaultdict(Decimal))
    first_invoice={}
    source_rows=0
    with ZipFile(path) as archive, ZipFile(BytesIO(archive.read('Online Retail.xlsx'))) as workbook:
        rows=source['workbook_rows'](workbook)
        assert list(next(rows).values())==['InvoiceNo','StockCode','Description','Quantity','InvoiceDate','UnitPrice','CustomerID','Country']
        for line in rows:
            source_rows+=1
            if 'G' not in line:
                continue
            who=line['G']
            stamp=Decimal(line['E'])
            day=int(stamp)
            quantity=int(line['D'])
            price=Decimal(line['F'])
            if price<=0:
                continue
            if line['A'].upper().startswith('C'):
                if quantity<0:
                    canceled[who][day]+=-quantity*price
                continue
            if quantity<=0:
                continue
            value=quantity*price
            positive[who][day]+=value
            key=(stamp,line['A'])
            if who not in first_invoice or key<first_invoice[who][0]:
                first_invoice[who]=[key,line.get('H',''),set(),Decimal(0)]
            invoice=first_invoice[who]
            code=line['B'].upper()
            if key==invoice[0] and PRODUCT.fullmatch(code):
                invoice[2].add(code)
                invoice[3]+=value
    def serial(d):
        return (d-source['ORIGIN']).days
    start,end=serial(source['FIRST']),serial(source['LAST'])
    rows=[]; later_pools=defaultdict(Counter); basket=defaultdict(Counter)
    for who,dated in positive.items():
        first=min(dated)
        if not start<=first<=end:
            continue
        other_days=sorted(day-first for day in dated if first<day<=first+180)
        first_later=other_days[0] if other_days else 181
        later=sum((v for day,v in dated.items() if first<day<=first+180),Decimal(0))
        loss=sum((v for day,v in canceled[who].items() if first<=day<=first+180),Decimal(0))
        rows.append((dated[first],later,loss))
        for cut,follow in ((14,30),(30,60),(60,90),(90,180)):
            group=later_pools[f'{cut}_to_{follow}']
            group['at_risk']+=first_later>cut
            group['first_repeats']+=cut<first_later<=follow
        _,country,codes,value=first_invoice[who]
        if not codes:
            continue
        size='1' if len(codes)==1 else '2–4' if len(codes)<=4 else '5–9' if len(codes)<=9 else '10+'
        market='UK' if country=='United Kingdom' else 'Outside UK'
        for scope,condition in [('All baskets',True),('£50 to under £150',50<=value<150)]:
            if condition:
                group=basket[(scope,market,size)]
                group['n']+=1
                group['repeats90']+=first_later<=90
                group['repeats180']+=first_later<=180
    assert source_rows==541909 and len(rows)==1549
    assert sum(x['n'] for (s,_,_),x in basket.items() if s=='All baskets')==1546
    assert sum(a+b for a,b,_ in rows).quantize(Decimal('.01'))==Decimal('1762299.44')
    assert sum(c for _,_,c in rows).quantize(Decimal('.01'))==Decimal('142438.28')
    def dollars(n):
        return float(n.quantize(Decimal('.01')))
    def money_summary(cohort):
        return {'buyers':len(cohort),'positive':dollars(sum((a+b for a,b,_ in cohort),Decimal(0))),
                'later':dollars(sum((b for _,b,_ in cohort),Decimal(0))),
                'cancel':dollars(sum((c for _,_,c in cohort),Decimal(0))),
                'canceled_buyers':sum(c>0 for _,_,c in cohort)}
    by_value=sorted(rows,key=lambda v: v[0]+v[1],reverse=True)
    by_cancel=sorted(rows,key=lambda v: v[2],reverse=True)
    out={}
    for n in (1,5,10,16,50):
        out[str(n)]={'top_value':money_summary(by_value[:n]),'top_cancel':money_summary(by_cancel[:n]),
                     'without_top_value':money_summary(by_value[n:]),'without_top_cancel':money_summary(by_cancel[n:])}
    return {'source_sha256':sha256(Path(path).read_bytes()).hexdigest(),'source_rows':source_rows,
            'full':money_summary(rows),'landmarks':dict(later_pools),'tail':out,
            'first_baskets':{' | '.join(k):v for k,v in sorted(basket.items())}}


if __name__=='__main__':
    reader=Path(sys.argv[2]) if len(sys.argv)>2 else Path(__file__).with_name('repeat-purchase-analysis.py')
    print(json.dumps(summarize(sys.argv[1],reader),indent=2,ensure_ascii=False))
