"""Measure later buying by first observed basket breadth in UCI Online Retail.

Run: python analysis_first_basket.py online-retail.zip
Keep repeat-purchase-analysis.py alongside this script. Requires Python 3.9+.
The output includes aggregate groups only.
"""
from collections import Counter, defaultdict
from datetime import timedelta
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
from statistics import median
import sys
from zipfile import ZipFile


PRODUCT = re.compile(r'\d{5}[A-Z]*', re.I)
BANDS = ('1','2–4','5–9','10+')


def band(count):
    if count==1:
        return BANDS[0]
    if count<=4:
        return BANDS[1]
    if count<=9:
        return BANDS[2]
    return BANDS[3]


def analyze(path, reader):
    source = run_path(str(reader), run_name='online_retail_reader')
    counters = Counter()
    by_customer = defaultdict(dict)
    with ZipFile(path) as archive, ZipFile(BytesIO(archive.read('Online Retail.xlsx'))) as workbook:
        lines = source['workbook_rows'](workbook)
        assert list(next(lines).values())==['InvoiceNo','StockCode','Description','Quantity','InvoiceDate','UnitPrice','CustomerID','Country']
        for line in lines:
            counters['source_rows'] += 1
            if 'G' not in line or line['A'].upper().startswith('C') or float(line['D'])<=0 or float(line['F'])<=0:
                continue
            who=line['G']
            item=line['B'].upper()
            stamp=Decimal(line['E'])
            invoice=by_customer[who].setdefault((stamp,line['A']),[set(),Decimal('0')])
            if PRODUCT.fullmatch(item):
                invoice[0].add(item)
                invoice[1] += Decimal(line['D'])*Decimal(line['F'])
    grouped=defaultdict(list)
    for invoices in by_customer.values():
        ordered=sorted(invoices.items())
        (stamp,_),(items,gross)=ordered[0]
        first=source['ORIGIN']+timedelta(days=int(stamp))
        if not source['FIRST']<=first<=source['LAST']:
            continue
        counters['date_eligible'] += 1
        if not items:
            counters['first_without_stock_code'] += 1
            continue
        later=sorted({int(key[0])-int(stamp) for key,_ in ordered if int(key[0])>int(stamp)})
        grouped[band(len(items))].append((gross,later))
    def summarize(rows):
        counts={'customers':len(rows),'median_first_value':float(median(gross for gross,_ in rows))}
        for days in (30,60,90,180):
            counts[f'repeated_{days}']=sum(bool(later) and later[0]<=days for _,later in rows)
        counts['days31_to_90']=counts['repeated_90']-counts['repeated_30']
        return counts
    groups={key:summarize(grouped[key]) for key in BANDS}
    within={key:summarize(selected) for key in BANDS
            if (selected:=[row for row in grouped[key] if 50<=row[0]<150])}
    assert counters['source_rows']==541909 and counters['date_eligible']==1549
    assert sum(g['customers'] for g in groups.values())+counters['first_without_stock_code']==1549
    return {'sha256':sha256(Path(path).read_bytes()).hexdigest(),'counts':dict(counters),'groups':groups,'within_50_to_150':within}


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(analyze(sys.argv[1],reader),indent=2))
