"""Python 3.11+, standard library. Synthetic OCR output, no image inference/API.
The gate checks provenance and arithmetic, not document authenticity.
"""
from decimal import Decimal, InvalidOperation
from copy import deepcopy
import unicodedata

def distance(a, b):
    row = list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        nxt = [i]
        for j, y in enumerate(b, 1):
            nxt.append(min(nxt[-1] + 1, row[j] + 1, row[j-1] + (x != y)))
        row = nxt
    return row[-1]

def cer(reference, prediction):
    # NFC Unicode code points; whitespace and case remain significant.
    a, b = (unicodedata.normalize('NFC', x) for x in (reference, prediction))
    if not a:
        raise ValueError('CER requires a nonempty reference')
    return distance(a, b) / len(a)

def validate(record, evidence):
    reasons = []
    values = {}
    for name in ('subtotal', 'tax', 'total'):
        field = record.get(name, {})
        source = evidence.get(field.get('evidence_id'))
        if not source or field.get('raw') != source.get('text'):
            reasons.append(name + ':missing_or_changed_evidence')
            continue
        bbox = source.get('bbox', [])
        if (source.get('page', 0) < 1 or len(bbox) != 4
            or not all(isinstance(x, (int, float)) and 0 <= x <= 1 for x in bbox)
            or not (bbox[0] < bbox[2] and bbox[1] < bbox[3])):
            reasons.append(name + ':invalid_source_region')
        # Fixed fixture convention: dot decimal, USD, no grouping separators.
        try:
            value = Decimal(field['raw'])
            if not value.is_finite() or value < 0 or value.as_tuple().exponent < -2:
                raise InvalidOperation
            values[name] = value
        except (InvalidOperation, ValueError, TypeError):
            reasons.append(name + ':unresolved_numeric_text')
    if record.get('currency') != 'USD':
        reasons.append('currency:unsupported')
    if record.get('account_changed'):
        reasons.append('account_change:independent_verification_required')
    if len(values) == 3 and values['subtotal'] + values['tax'] != values['total']:
        reasons.append('amounts:inconsistent')
    return ('review' if reasons else 'validated_candidate'), reasons

E = {k: {'text': v, 'page': 1, 'bbox': [0.6, y, 0.9, y + .04]}
     for k, v, y in [('s', '1000.00', .6), ('t', '80.00', .7), ('g', '1080.00', .8)]}
R = {'currency': 'USD', 'account_changed': False,
     **{n: {'raw': E[k]['text'], 'evidence_id': k}
        for n, k in [('subtotal', 's'), ('tax', 't'), ('total', 'g')]}}

def main():
    assert validate(R, E)[0] == 'validated_candidate'
    wrong = deepcopy(R); wrong['total']['raw'] = '1090.00'
    assert validate(wrong, E)[0] == 'review'  # invented correction has no evidence
    ambiguous = deepcopy(R); ambiguous['total']['raw'] = '1O80.00'
    ambiguous_e = deepcopy(E); ambiguous_e['g']['text'] = '1O80.00'
    assert validate(ambiguous, ambiguous_e)[0] == 'review'  # never guess O -> 0
    bad_sum_e = deepcopy(E); bad_sum_e['g']['text'] = '1090.00'
    bad_sum = deepcopy(R); bad_sum['total']['raw'] = '1090.00'
    assert validate(bad_sum, bad_sum_e)[0] == 'review'  # evidence exists, sum fails
    missing = deepcopy(R); missing['total']['evidence_id'] = 'not-found'
    assert validate(missing, E)[0] == 'review'
    changed = deepcopy(R); changed['account_changed'] = True
    assert validate(changed, E)[0] == 'review'
    bad_box = deepcopy(E); bad_box['g']['bbox'] = [.9, .8, .6, .7]
    assert validate(R, bad_box)[0] == 'review'
    nonfinite = deepcopy(R); nonfinite['total']['raw'] = 'NaN'
    nonfinite_e = deepcopy(E); nonfinite_e['g']['text'] = 'NaN'
    assert validate(nonfinite, nonfinite_e)[0] == 'review'
    assert cer('1080.00', '1O80.00') == 1 / 7
    assert cer('café', 'cafe\u0301') == 0
    print('checks=11 clean=validated_candidate ambiguous=review cer=0.142857')
    print('synthetic_cost=1600.00 cost_per_validated_document=0.20')
    assert Decimal(10000) * Decimal('.01') + Decimal(10000) * Decimal('.15') * Decimal('.08') + Decimal(10000) * Decimal('.05') * Decimal('2') + Decimal('380') == Decimal('1600')
    # A real deployment also needs authentication, anti-tamper checks, taxes/rounding
    # rules, independent payment authority and immutable source versioning.
if __name__ == '__main__':
    main()
