"""Synthetic single-choice record comparison; not tabulation or an RLA."""
import json


def index_records(rows):
    indexed = {}
    for row in rows:
        if not isinstance(row, dict) or set(row) != {'record_id', 'selection'}:
            raise ValueError('Expected record_id and selection only')
        key, selection = row['record_id'], row['selection']
        if not isinstance(key, str) or not key or key in indexed:
            raise ValueError('Missing or duplicate record_id')
        if not isinstance(selection, str) or not selection:
            raise ValueError('Expected a nonempty synthetic selection label')
        indexed[key] = selection
    return indexed


def compare_records(machine_rows, inspection_rows):
    machine = index_records(machine_rows)
    inspection = index_records(inspection_rows)
    common = sorted(machine.keys() & inspection.keys())
    return {
        'compared': len(common),
        'mismatches': [
            {'record_id': key, 'machine': machine[key], 'inspection': inspection[key]}
            for key in common if machine[key] != inspection[key]
        ],
        'missing_inspection': sorted(machine.keys() - inspection.keys()),
        'missing_machine': sorted(inspection.keys() - machine.keys()),
        'risk_limit_computed': False,
        'election_outcome_verified': False,
    }


def self_test():
    normal = [{'record_id': 'fixture-1', 'selection': 'Option A'}]
    changed = [{'record_id': 'fixture-1', 'selection': 'Option B'}]
    assert compare_records(normal, normal)['mismatches'] == []
    assert len(compare_records(changed, normal)['mismatches']) == 1
    assert compare_records(normal, [])['missing_inspection'] == ['fixture-1']
    assert compare_records([], normal)['missing_machine'] == ['fixture-1']
    assert compare_records([], [])['compared'] == 0
    for bad in (normal + normal, [{'record_id': '', 'selection': 'A'}],
                [{'record_id': 'fixture-2', 'selection': None}]):
        try:
            compare_records(bad, normal)
        except ValueError:
            pass
        else:
            raise AssertionError('Invalid records accepted')
    result = compare_records(changed, normal)
    assert result['risk_limit_computed'] is False
    assert result['election_outcome_verified'] is False
    print(json.dumps(result, indent=2))
    print('10 synthetic checks passed; no election data or equipment accessed')


if __name__ == '__main__':
    self_test()
