# Place the UCI online-retail.zip archive next to this script. Requires Python 3.9 or newer.
"""Compute comparable fixed-window and immature-cohort results from UCI Online Retail.

Place the UCI online-retail.zip archive next to this file. Python 3.9 or later.
Only aggregate results are written to stdout. The workbook remains the source.
"""
from collections import Counter, defaultdict
from datetime import date, timedelta
from decimal import Decimal
from statistics import median
from hashlib import sha256
from io import BytesIO
import json
from pathlib import Path
import sys
from xml.etree.ElementTree import iterparse
from zipfile import ZipFile

HERE = Path(__file__).resolve().parent
NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
ORIGIN = date(1899, 12, 30)
FIRST = date(2011, 1, 1)
LAST = date(2011, 4, 30)
END = date(2011, 12, 9)
SNAPSHOT = date(2011, 5, 31)
WINDOWS = (14, 30, 60, 90, 120, 180)

def workbook_rows(workbook):
    with workbook.open('xl/sharedStrings.xml') as stream:
        strings = [''.join(e.itertext()) for _, e in iterparse(stream) if e.tag == NS+'si']
    with workbook.open('xl/worksheets/sheet1.xml') as stream:
        for event, e in iterparse(stream, events=('start','end')):
            if event == 'start' and e.tag == NS+'sheetData':
                parent = e
            if event == 'end' and e.tag == NS+'row':
                values = {}
                for cell in e:
                    v = cell.findtext(NS+'v')
                    if v is not None:
                        values[cell.get('r')[0]] = strings[int(v)] if cell.get('t') == 's' else v
                yield values
                parent.remove(e)

def qualified_cohort(path):
    rows_seen = Counter()
    dates = defaultdict(set)
    with ZipFile(path) as archive, ZipFile(BytesIO(archive.read('Online Retail.xlsx'))) as book:
        rows = workbook_rows(book)
        assert list(next(rows).values()) == ['InvoiceNo','StockCode','Description','Quantity',
                                             'InvoiceDate','UnitPrice','CustomerID','Country']
        for row in rows:
            rows_seen['source_rows'] += 1
            if 'G' not in row:
                rows_seen['anonymous'] += 1
            elif row['A'].upper().startswith('C') or float(row['D']) <= 0 or float(row['F']) <= 0:
                rows_seen['nonpurchase'] += 1
            else:
                rows_seen['positive_identified'] += 1
                dates[row['G']].add(ORIGIN+timedelta(days=int(float(row['E']))))
    cohort = []
    for values in dates.values():
        visits = sorted(values)
        if FIRST <= visits[0] <= LAST:
            cohort.append(visits)
    return cohort, rows_seen

def share(n, d):
    if not 0 <= n <= d or not d:
        raise ValueError(f'Invalid numerator or denominator: {n}/{d}')
    return {'n':n,'denominator':d,'percent':round(100*n/d,2)}

def horizons(cohort, windows, cutoff):
    results = {}
    for days in windows:
        usable = [visits for visits in cohort if visits[0]+timedelta(days=days) <= cutoff]
        completed = sum(len(visits)>1 and (visits[1]-visits[0]).days<=days for visits in usable)
        if usable:
            results[days] = share(completed,len(usable))
    return results

def snapshot(cohort, days):
    cut = [visits for visits in cohort if visits[0]<=SNAPSHOT]
    naive = sum(len(v)>1 and v[1]<=SNAPSHOT and (v[1]-v[0]).days<=days for v in cut)
    mature = horizons(cut,[days],SNAPSHOT)[days]
    return {'naive':share(naive,len(cut)),'mature':mature,'immature_count':len(cut)-mature['denominator']}

def run(path):
    before = date(2011, 2, 1)
    after = date(2011, 4, 1)
    toy = [[before,before+timedelta(days=15)], [after,after+timedelta(days=15)], [before]]
    assert horizons(toy,[90],date(2011,5,5)) == {90:share(1,2)}
    assert horizons(toy,[30],date(2011,5,5)) == {30:share(2,3)}
    cohort, counts = qualified_cohort(path)
    assert len(cohort)==1549 and counts['source_rows']==541909
    assert LAST+timedelta(days=max(WINDOWS)) <= END
    full = horizons(cohort,WINDOWS,END)
    monthly = {
        date(2011,m,1).strftime('%B'): horizons([v for v in cohort if v[0].month==m],(30,60,90,180),END)
        for m in range(1,5)
    }
    depth = {}
    for day in (30,90,180):
        depth[day] = {}
        for repeat_dates in (1,2,3):
            n=sum(len(v)>repeat_dates and (v[repeat_dates]-v[0]).days<=day for v in cohort)
            depth[day][repeat_dates]=share(n,len(cohort))
    no_repeat_at_30=len(cohort)-full[30]['n']
    no_repeat_at_90=len(cohort)-full[90]['n']
    later={
        'days_31_to_90':share(full[90]['n']-full[30]['n'],no_repeat_at_30),
        'days_91_to_180':share(full[180]['n']-full[90]['n'],no_repeat_at_90),
    }
    for d in (30,60,90,180):
        assert sum(m[d]['n'] for m in monthly.values())==full[d]['n']
        assert sum(m[d]['denominator'] for m in monthly.values())==len(cohort)
    assert depth[90][1]==full[90] and full[30]['n']==227 and full[180]['n']==966
    return {'source_sha256':sha256(path.read_bytes()).hexdigest(),'rows':counts,'cohort':len(cohort),
            'full':full,'monthly':monthly,'depth':depth,'later':later,'snapshot_date':str(SNAPSHOT),
            'snapshot':{d:snapshot(cohort,d) for d in (60,90)}}

def cohort_value(path):
    """Summarize gross recorded line value and sensitivity to counting invoices."""
    customer = defaultdict(lambda: defaultdict(lambda: [Decimal(0), set()]))
    with ZipFile(path) as archive, ZipFile(BytesIO(archive.read('Online Retail.xlsx'))) as book:
        records = workbook_rows(book)
        assert list(next(records).values()) == ['InvoiceNo','StockCode','Description','Quantity',
                                                'InvoiceDate','UnitPrice','CustomerID','Country']
        for row in records:
            if 'G' not in row or row['A'].upper().startswith('C'):
                continue
            quantity = int(row['D'])
            price = Decimal(row['F'])
            if quantity <= 0 or price <= 0:
                continue
            day = ORIGIN + timedelta(days=int(Decimal(row['E'])))
            bucket = customer[row['G']][day]
            bucket[0] += quantity * price
            bucket[1].add(row['A'])
    eligible = [(dates, min(dates)) for dates in customer.values() if FIRST <= min(dates) <= LAST]
    assert len(eligible) == 1549
    groups = defaultdict(list)
    horizons = {30:Counter(),90:Counter(),180:Counter()}
    for dates, start in eligible:
        values = [(day, value, invoices) for day,(value,invoices) in sorted(dates.items()) if day<=start+timedelta(days=180)]
        n = len(values)
        group = '1' if n==1 else '2' if n==2 else '3–4' if n<=4 else '5+'
        first = values[0][1]
        later = sum(v for _,v,_ in values[1:])
        groups[group].append((first, later))
        for window, c in horizons.items():
            visits = [(day,v,invoice) for day,v,invoice in values if day<=start+timedelta(days=window)]
            c['date_repeat'] += len(visits)>1
            count = len(set().union(*(invoices for _,_,invoices in visits)))
            assert len(visits)<=1 or count>1
            c['invoice_repeat'] += count>1
            c['multiple_first_date_invoices'] += len(visits[0][2])>1
    summary = {}
    overall = sum((first+later for items in groups.values() for first,later in items), Decimal(0))
    money = lambda value: float(round(Decimal(value),2))
    for key in ('1','2','3–4','5+'):
        items = groups[key]
        first = sum(a for a,_ in items)
        later = sum(b for _,b in items)
        summary[key] = {'customers':len(items),'customer_percent':round(100*len(items)/len(eligible),2),
            'first':money(first),'later':money(later),'total':money(first+later),'value_percent':round(float(100*(first+later)/overall),2),
            'median_total':money(median(a+b for a,b in items))}
    assert sum(x['customers'] for x in summary.values())==len(eligible)
    assert all(c['invoice_repeat']>=c['date_repeat'] for c in horizons.values())
    assert [c['date_repeat'] for c in horizons.values()]==[227,657,966]
    return {'source_sha256':sha256(path.read_bytes()).hexdigest(),'cohort':len(eligible),'total_gbp':money(overall),
            'groups':summary,'horizons':horizons,'follow_up_days':180}

def cancellation_analysis(path):
    """Aggregate positive and canceled lines without claiming order-level refund matching."""
    purchases=defaultdict(lambda: defaultdict(Decimal))
    canceled=defaultdict(lambda: defaultdict(Decimal))
    line_counts=Counter()
    with ZipFile(path) as archive, ZipFile(BytesIO(archive.read('Online Retail.xlsx'))) as book:
        records=workbook_rows(book)
        assert list(next(records).values())==['InvoiceNo','StockCode','Description','Quantity',
                                                'InvoiceDate','UnitPrice','CustomerID','Country']
        for row in records:
            line_counts['workbook']+=1
            if 'G' not in row:
                continue
            quantity=int(row['D'])
            price=Decimal(row['F'])
            if price<=0:
                continue
            day=ORIGIN+timedelta(days=int(Decimal(row['E'])))
            is_cancel=row['A'].upper().startswith('C')
            if is_cancel and quantity<0:
                canceled[row['G']][day]+=-quantity*price
                line_counts['identified_negative_cancel']+=1
            elif not is_cancel and quantity>0:
                purchases[row['G']][day]+=quantity*price
                line_counts['identified_positive']+=1
    assert line_counts['workbook']==541909
    cohort=[(cid,sorted(days),days) for cid,days in purchases.items() if FIRST<=min(days)<=LAST]
    assert len(cohort)==1549
    groups=defaultdict(list)
    windows=defaultdict(list)
    first_amounts=defaultdict(list)
    conditional=Counter()
    for cid,days,amounts in cohort:
        first=days[0]
        repeated=[(day-first).days for day in days[1:]]
        returned_30=bool(repeated and repeated[0]<=30)
        conditional['repeat30' if returned_30 else 'no_repeat30']+=1
        conditional['repeat30_two_by90' if returned_30 else 'no_repeat30_two_by90']+=sum(d<=90 for d in repeated)>=2
        for horizon in (30,90,180):
            end=first+timedelta(days=horizon)
            eligible=[d for d in days if d<=end]
            gross=sum((amounts[d] for d in eligible),Decimal(0))
            cancellation=sum((v for d,v in canceled.get(cid,{}).items() if first<=d<=end),Decimal(0))
            windows[horizon].append((gross,cancellation))
            if horizon==180:
                group='1' if len(eligible)==1 else '2' if len(eligible)==2 else '3–4' if len(eligible)<=4 else '5+'
                groups[group].append((gross,cancellation))
                first_amounts[group].append(amounts[first])
    money=lambda value:float(round(Decimal(value),2))
    def summarize(values):
        gross=sum(a for a,_ in values)
        losses=sum(b for _,b in values)
        positive_cancels=[b for _,b in values if b>0]
        return {'customers':len(values),'with_canceled_line':len(positive_cancels),
                'gross':money(gross),'canceled_value':money(losses),
                'difference':money(gross-losses),'value_ratio_pct':round(float(losses/gross*100),2),
                'customer_share_pct':round(100*len(positive_cancels)/len(values),2)}
    whole={k:summarize(v) for k,v in windows.items()}
    breakdown={k:summarize(groups[k]) for k in ('1','2','3–4','5+')}
    stats={k:{'median_first_date':money(median(first_amounts[k])),
              'mean_first_date':money(sum(first_amounts[k])/len(first_amounts[k])),
              'customers':len(first_amounts[k])} for k in breakdown}
    assert whole[180]['gross']==1762299.44 and conditional['repeat30']==227
    assert sum(x['with_canceled_line'] for x in breakdown.values())==whole[180]['with_canceled_line']
    assert sum(Decimal(str(x['canceled_value'])) for x in breakdown.values())==Decimal(str(whole[180]['canceled_value']))
    return {'source_sha256':sha256(path.read_bytes()).hexdigest(),'cohort':len(cohort),
            'windows':whole,'groups':breakdown,'conditional':conditional,'first_purchase_value':stats,'line_counts':line_counts}

if __name__=='__main__':
    args=sys.argv[1:]
    selected=[x for x in ('--value','--cancellations') if x in args]
    if len(selected)>1:
        raise SystemExit('Choose one analysis mode.')
    files=[x for x in args if x not in selected]
    source=Path(files[0]) if files else HERE/'uci-online-retail.zip'
    method={'--value':cohort_value,'--cancellations':cancellation_analysis}.get(selected[0],run) if selected else run
    print(json.dumps(method(source),indent=2,ensure_ascii=False))
