"""Reconcile six invented approval events; Python standard library, no network."""
from collections import Counter
from copy import deepcopy
import json


def event(ident, deal, attempt, revision, step, actor, original, status, comment):
    return dict(id=ident, deal=deal, attempt=attempt, revision=revision,
                step=step, actor=actor, original_actor=original,
                status=status, comment=comment)


source = [
    event('E1', 'A', 'A-first', 'A-v1', 1, 'manager', 'manager', 'Rejected', 'Revise discount'),
    event('E2', 'A', 'A-second', 'A-v2', 1, 'manager', 'manager', 'Approved', 'Revised discount accepted'),
    event('E3', 'A', 'A-second', 'A-v2', 2, 'legal-delegate', 'legal-lead', 'Approved', 'Revised terms accepted'),
    event('E4', 'B', 'B-first', 'B-v1', 1, 'manager', 'manager', 'Approved', 'Commercial terms accepted'),
    event('E5', 'B', 'B-first', 'B-v1', 2, 'legal-lead', 'legal-lead', 'Approved', 'Approve only annual billing'),
    event('E6', 'C', 'C-first', 'C-v1', 1, 'manager', 'manager', 'Rejected', 'Missing scope'),
]
current = {'A': 'A-second', 'B': 'B-first', 'C': 'C-first'}
damaged = deepcopy(source)
damaged[0]['attempt'], damaged[1]['attempt'] = damaged[1]['attempt'], damaged[0]['attempt']
damaged[2]['actor'] = damaged[2]['original_actor']
damaged[3]['revision'] = 'B-v2'
damaged[4]['comment'] = 'Approve monthly billing'
wrong_current = dict(current, A='A-first')


def reconcile(actual, pointers):
    expected = {row['id']: row for row in source}
    identities = Counter(row['id'] for row in actual)
    discrepancies = []
    for row in actual:
        reference = expected.get(row['id'])
        if reference is None:
            discrepancies.append({'id': row['id'], 'fields': ['unexpected identity']})
            continue
        fields = [key for key in reference if row.get(key) != reference[key]]
        if identities[row['id']] != 1:
            fields.append('identity multiplicity')
        if fields:
            discrepancies.append({'id': row['id'], 'fields': fields})
    missing = sorted(set(expected) - set(identities))
    pointer_errors = sorted(key for key in set(current) | set(pointers)
                            if current.get(key) != pointers.get(key))
    return dict(event_count=len(actual), decision_totals=dict(Counter(r['status'] for r in actual)),
                discrepancies=discrepancies, missing=missing,
                current_attempt_errors=pointer_errors,
                passed=not (discrepancies or missing or pointer_errors))


if __name__ == '__main__':
    baseline = reconcile(source, current)
    faulty = reconcile(damaged, wrong_current)
    assert baseline['passed']
    assert baseline['event_count'] == faulty['event_count'] == 6
    assert baseline['decision_totals'] == faulty['decision_totals'] == {'Rejected': 2, 'Approved': 4}
    assert [r['id'] for r in faulty['discrepancies']] == ['E1', 'E2', 'E3', 'E4', 'E5']
    assert faulty['current_attempt_errors'] == ['A']
    print(json.dumps({'baseline': baseline, 'damaged': faulty}, indent=2))
