"""Reproduce the cohort using the UCI Online Retail II ZIP passed as an argument."""
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict
from datetime import date
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

NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
ORIGIN = date(1899, 12, 30)
FIRST = (date(2011, 1, 1) - ORIGIN).days
LAST = (date(2011, 4, 30) - ORIGIN).days
LATER_SHEET_START = (date(2010, 12, 1) - ORIGIN).days
LOOKBACKS = (30, 90, 180, 365, None)


def rows(book, sheet, strings):
    with book.open(f'xl/worksheets/sheet{sheet}.xml') as stream:
        for event, element in iterparse(stream, events=('start', 'end')):
            if event == 'start' and element.tag == NS+'sheetData':
                parent = element
            if event == 'end' and element.tag == NS+'row':
                row = {}
                for cell in element:
                    value = cell.findtext(NS+'v')
                    if value is not None:
                        row[cell.get('r')[0]] = strings[int(value)] if cell.get('t') == 's' else value
                yield row
                parent.remove(element)


def classify(days, first):
    index = bisect_left(days, first)
    before = days[index-1] if index else None
    return (first-before if before is not None else None,
            bisect_right(days, first+90) > index+1)


def analyze(path):
    assert classify([50, 100, 191], 100) == (50, False)
    assert classify([10, 100], 10) == (None, True)
    all_days, later_days = defaultdict(set), defaultdict(set)
    counts = Counter()
    with ZipFile(path) as source, ZipFile(BytesIO(source.read('online_retail_II.xlsx'))) as book:
        with book.open('xl/sharedStrings.xml') as stream:
            strings = [''.join(e.itertext()) for _, e in iterparse(stream) if e.tag == NS+'si']
        for sheet in (1, 2):
            records = rows(book, sheet, strings)
            header = next(records)
            assert list(header) == list('ABCDEFGH') and 'Customer' in header['G'], header
            for row in records:
                counts[f'sheet_{sheet}_rows'] += 1
                if 'G' not in row or row['A'].upper().startswith('C') or float(row['D']) <= 0 or float(row['F']) <= 0:
                    continue
                counts[f'sheet_{sheet}_eligible_lines'] += 1
                day = int(float(row['E']))
                all_days[row['G']].add(day)
                if sheet == 2:
                    assert day >= LATER_SHEET_START
                    later_days[row['G']].add(day)
    targets = [(sorted(all_days[customer]), min(days)) for customer, days in later_days.items()
               if FIRST <= min(days) <= LAST]
    assert all(max(days) <= (date(2011, 12, 9)-ORIGIN).days for days, _ in targets)
    assert LAST+90 <= (date(2011, 12, 9)-ORIGIN).days
    checks = [classify(days, first) for days, first in targets]
    windows = {}
    for limit in LOOKBACKS:
        flagged = [rep for ago, rep in checks if ago is not None and (limit is None or ago <= limit)]
        unflagged = [rep for ago, rep in checks if ago is None or (limit is not None and ago > limit)]
        windows[str(limit)] = dict(flagged=len(flagged), unflagged=len(unflagged),
                                   flagged_repeat=sum(flagged), unflagged_repeat=sum(unflagged))
    return dict(sha256=sha256(Path(path).read_bytes()).hexdigest(), rows=counts,
                cohort=len(targets), windows=windows)


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