"""Invented reconciliation fixture. Run with Python 3; standard library only."""
from copy import deepcopy
from decimal import Decimal, ROUND_HALF_UP
import json

BASE = [
    dict(id='L1', deal='D1', product='SEAT', currency='USD', quantity='3', price='100', discount_type='percent', discount='10', period='month'),
    dict(id='L2', deal='D1', product='SETUP', currency='USD', quantity='2', price='120', discount_type='fixed_line', discount='0', period='once'),
    dict(id='L3', deal='D2', product='SEAT', currency='USD', quantity='1', price='100', discount_type='fixed_line', discount='0', period='month'),
]

def totals(rows):
    out = {}
    for row in rows:
        gross = Decimal(row['quantity']) * Decimal(row['price'])
        discount = Decimal(row['discount'])
        net = gross * (1-discount/100) if row['discount_type']=='percent' else gross-discount
        net = net.quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
        key = row['deal'] + '/' + row['currency']
        out[key] = out.get(key, Decimal('0')) + net
    return {k: str(v) for k,v in sorted(out.items())}

def exact(rows):
    # List sorting retains duplicate occurrences; no set-based deduplication.
    return sorted(tuple(sorted(row.items())) for row in rows)

def candidate(changes):
    rows = deepcopy(BASE)
    for i, patch in changes:
        rows[i].update(patch)
    return rows

cases = {
    'correct': deepcopy(BASE),
    'offset_quantities': candidate([(0,dict(quantity='4')),(1,dict(quantity='1.25'))]),
    'wrong_product': candidate([(0,dict(product='SUPPORT'))]),
    'wrong_period': candidate([(0,dict(period='year'))]),
    'discount_type_changed': candidate([(0,dict(discount_type='fixed_line'))]),
    'catalog_price_replaces_agreed_price': candidate([(0,dict(price='110'))]),
    'duplicate_replaces_line': [deepcopy(BASE[0]),deepcopy(BASE[0]),deepcopy(BASE[2])],
    'missing_line': deepcopy(BASE[:2]),
}
report = {'expected_totals': totals(BASE), 'cases': {}}
for name, rows in cases.items():
    report['cases'][name] = dict(rows=len(rows), count_pass=len(rows)==len(BASE), totals=totals(rows), totals_pass=totals(rows)==totals(BASE), exact_pass=exact(rows)==exact(BASE))
assert report['expected_totals']=={'D1/USD':'510.00','D2/USD':'100.00'}
assert report['cases']['correct']['exact_pass']
assert all(not v['exact_pass'] for k,v in report['cases'].items() if k!='correct')
assert sum(v['count_pass'] and v['totals_pass'] and not v['exact_pass'] for v in report['cases'].values())==3
print(json.dumps(report,indent=2))
