#!/usr/bin/env python3
"""Independent exact OBV/CMF20 replay; no production module is read or imported."""
import argparse
import copy
import json
import math
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from hashlib import sha256
from pathlib import Path

PINNED_PROTOCOL = 'e46b7ee7e4c7018c8781f45ca635affd22082654a50e61add7b870fe850eef1d'
PINNED_SOURCE = '060f24b65562a768dde311f7e6ff09ba69c4bc99c2c2457e46dd7b2bc95b88ad'
SCALE = 100000000
INTERVAL = 14400
PERIOD = 20
RAW = ('ts', 'open', 'high', 'low', 'close', 'volume', 'source_close_raw', 'timestamp_scale')
INTS = ('open', 'high', 'low', 'close', 'volume')
STATE = ('previous_close', 'direction', 'signed_volume', 'signed_volume_int', 'obv', 'obv_int',
         'mfm', 'mfm_num', 'mfm_den', 'mfv', 'mfv_num', 'mfv_den',
         'window_volume', 'window_volume_int', 'window_mfv', 'window_mfv_num', 'window_mfv_den',
         'cmf', 'cmf_num', 'cmf_den', 'obv_change20', 'obv_change20_int',
         'obv_balance20', 'obv_balance20_num', 'obv_balance20_den')


class VerificationError(Exception):
    pass


def require(condition, message):
    if not condition:
        raise VerificationError(message)


def checksum(path):
    return sha256(Path(path).read_bytes()).hexdigest()


def unique_pairs(pairs):
    out = {}
    for key, value in pairs:
        require(key not in out, 'Duplicate JSON key: '+key)
        out[key] = value
    return out


def read(path):
    return json.loads(Path(path).read_text(encoding='utf-8'), object_pairs_hook=unique_pairs)


def as_integer(value, label):
    require(type(value) in (int, float), label+': finite numeric input required')
    try:
        number = Decimal(str(value)) * SCALE
    except InvalidOperation as error:
        raise VerificationError(label+': invalid decimal') from error
    require(number.is_finite() and number == number.to_integral_value(), label+': unrepresentable precision')
    return int(number)


def output_fraction(row, name, value):
    if value is None:
        row.update({name: None, name+'_num': None, name+'_den': None})
    else:
        value = Fraction(value)
        row.update({name: float(value), name+'_num': value.numerator, name+'_den': value.denominator})


def replay(observations):
    """Use independent prefix lists and direct window summation, not a rolling recurrence."""
    result, exact = [], []
    active = []
    prior_raw_ts = None
    for index, source in enumerate(observations):
        require(isinstance(source, dict), f'Input {index}: object required')
        require(all(k in source for k in RAW), f'Input {index}: missing raw field')
        row = {k: source[k] for k in RAW}
        anchor, unit = row['ts'], row['timestamp_scale']
        require(type(anchor) is int and anchor % INTERVAL == 0, f'Input {index}: invalid anchor')
        if prior_raw_ts is not None:
            require(anchor > prior_raw_ts and (anchor-prior_raw_ts) % INTERVAL == 0,
                    f'Input {index}: unordered/nonaligned anchors')
        require(type(unit) is int and unit in (1000, 1000000), f'Input {index}: invalid timestamp scale')
        require(type(row['source_close_raw']) is int, f'Input {index}: invalid close label')
        integer = {k: as_integer(row[k], f'Input {index}.{k}') for k in INTS}
        require(0 < integer['low'] <= min(integer['open'], integer['close']) <=
                max(integer['open'], integer['close']) <= integer['high'], f'Input {index}: invalid OHLC bounds')
        require(integer['volume'] >= 0, f'Input {index}: negative volume')
        row.update({k+'_int': v for k, v in integer.items()})
        canonical = row['source_close_raw'] == (anchor+INTERVAL)*unit-1
        adjacent = prior_raw_ts is not None and anchor-prior_raw_ts == INTERVAL
        if not canonical or not adjacent:
            active = []
        row.update({k: None for k in STATE})
        mfm = mfv = cmf = balance = None
        if canonical:
            previous = active[-1] if active else None
            mfm = (Fraction(2*integer['close']-integer['high']-integer['low'], integer['high']-integer['low'])
                   if integer['high'] != integer['low'] else Fraction(0))
            mfv = mfm * Fraction(integer['volume'], SCALE)
            if previous is None:
                obv_int, change = 0, None
            else:
                direction = (integer['close'] > previous['close_int']) - (integer['close'] < previous['close_int'])
                change = direction * integer['volume']
                obv_int = previous['obv_int'] + change
                row.update(previous_close=previous['close'], direction=direction,
                           signed_volume=float(Fraction(change, SCALE)), signed_volume_int=change)
            row.update(obv=float(Fraction(obv_int, SCALE)), obv_int=obv_int)
            entry = dict(integer, close=row['close'], close_int=integer['close'],
                         obv_int=obv_int, change=change, mfv=mfv)
            active.append(entry)
            run = len(active)
            if run >= PERIOD:
                window = active[-PERIOD:]
                volume_sum = sum(v['volume'] for v in window)
                flow_sum = sum((v['mfv'] for v in window), Fraction(0))
                row.update(window_volume=float(Fraction(volume_sum, SCALE)), window_volume_int=volume_sum)
                output_fraction(row, 'window_mfv', flow_sum)
                cmf = flow_sum / Fraction(volume_sum, SCALE) if volume_sum else None
                if run >= PERIOD+1:
                    signed_sum = sum(v['change'] for v in window)
                    require(signed_sum == obv_int-active[-PERIOD-1]['obv_int'], 'Independent OBV window identity')
                    row.update(obv_change20=float(Fraction(signed_sum, SCALE)), obv_change20_int=signed_sum)
                    balance = Fraction(signed_sum, volume_sum) if volume_sum else None
            row.update(canonical=True, canonical_run=run, window_bars=min(run, PERIOD))
        else:
            row.update(canonical=False, canonical_run=0, window_bars=0)
        output_fraction(row, 'mfm', mfm)
        output_fraction(row, 'mfv', mfv)
        output_fraction(row, 'cmf', cmf)
        output_fraction(row, 'obv_balance20', balance)
        require(mfm is None or -1 <= mfm <= 1, 'MFM bound')
        require(cmf is None or -1 <= cmf <= 1, 'CMF bound')
        require(balance is None or -1 <= balance <= 1, 'Normalized OBV bound')
        result.append(row)
        exact.append({'mfm': mfm, 'mfv': mfv, 'cmf': cmf, 'balance': balance})
        prior_raw_ts = anchor
    return result, exact


def select(rows, values, protocol):
    chosen, used, eligible_counts = [], set(), {}
    start = protocol['selection']['start_ts']
    for tag in protocol['selection']['order']:
        found, count = None, 0
        for index, (row, precise) in enumerate(zip(rows, values)):
            if (row['ts'] < start or index < 25 or index+5 >= len(rows) or index in used
                    or row['canonical_run'] < 26):
                continue
            cmf = precise['cmf']
            if tag == 'obv_up_cmf_down':
                match = row['obv_change20_int'] is not None and row['obv_change20_int'] > 0 and cmf is not None and cmf < 0
            elif tag == 'obv_down_cmf_up':
                match = row['obv_change20_int'] is not None and row['obv_change20_int'] < 0 and cmf is not None and cmf > 0
            elif tag == 'bar_disagrees':
                match = (row['direction'] == 1 and precise['mfm'] is not None and precise['mfm'] < 0
                         and row['volume_int'] > 0 and cmf is not None and precise['balance'] is not None)
            else:
                raise VerificationError('Unknown selection predicate: '+tag)
            if match:
                count += 1
                if found is None:
                    found = {'tag': tag, 'index': index, 'signal_ts': row['ts'],
                             'available_ts': row['ts']+INTERVAL, 'reference_index': 25,
                             'signal_values': row, 'previous_values': rows[index-1],
                             'bars': rows[index-25:index+6]}
        require(found is not None, 'No eligible example: '+tag)
        chosen.append(found)
        used.add(found['index'])
        eligible_counts[tag] = count
    return chosen, eligible_counts


def compare(actual, expected, path, report):
    require(type(actual) is type(expected), path+f': type {type(actual).__name__} != {type(expected).__name__}')
    if isinstance(expected, dict):
        require(set(actual) == set(expected), path+': keys differ '+str(set(actual)^set(expected)))
        for key in expected:
            compare(actual[key], expected[key], path+'.'+str(key), report)
    elif isinstance(expected, list):
        require(len(actual) == len(expected), path+': list length mismatch')
        for index, value in enumerate(expected):
            compare(actual[index], value, path+f'[{index}]', report)
    else:
        if isinstance(expected, float):
            require(math.isfinite(actual), path+': nonfinite output')
        require(actual == expected, path+f': {str(actual)[:80]} != {str(expected)[:80]}')
        report['scalar_comparisons'] += 1


def verify_teaching(teaching):
    assertions = 0
    first = teaching['classification']
    high, low, volume = map(Fraction, (first['high'], first['low'], first['volume']))
    for case in first['cases']:
        close, previous = Fraction(case['close']), Fraction(case['previous_close'])
        mfm = (2*close-high-low)/(high-low)
        direction = (close > previous) - (close < previous)
        require(Fraction(case['signed_volume']) == direction*volume, 'Teaching signed volume '+case['id'])
        require(Fraction(str(case['mfm'])) == mfm, 'Teaching MFM '+case['id'])
        require(Fraction(case['mfv']) == mfm*volume, 'Teaching MFV '+case['id'])
        assertions += 3
    second = teaching['denominator']
    b = second['ranged_bar']
    ranged_mfm = Fraction(2*b['close']-b['high']-b['low'], b['high']-b['low'])
    require(second['flat_bar']['high'] == second['flat_bar']['low'] == second['flat_bar']['close'], 'Teaching flat range')
    assertions += 1
    for case in second['cases']:
        require(case['ranged_rows']+case['flat_rows'] == PERIOD == second['period'], 'Teaching twenty-bar count')
        denominator = PERIOD*Fraction(case['volume_each'])
        numerator = case['ranged_rows']*ranged_mfm*Fraction(case['volume_each'])
        cmf = numerator/denominator if denominator else None
        require(Fraction(case['window_volume']) == denominator, 'Teaching denominator '+case['id'])
        require(Fraction(case['window_mfv']) == numerator, 'Teaching numerator '+case['id'])
        require((None if case['cmf'] is None else Fraction(str(case['cmf']))) == cmf, 'Teaching ratio '+case['id'])
        assertions += 4
    return {'figures': 2, 'cases': 8, 'assertions': assertions}


def fixture(close, high=None, low=None, volume=10, index=0, scale=1000, canonical=True):
    anchor = 1672531200+index*INTERVAL
    high = close+2 if high is None else high
    low = close-2 if low is None else low
    return dict(ts=anchor, open=close, high=high, low=low, close=close, volume=volume,
                source_close_raw=(anchor+INTERVAL)*scale-1-(0 if canonical else 1), timestamp_scale=scale)


def synthetic_checks():
    cases, assertion_count = [], 0
    def case(name, check):
        nonlocal assertion_count
        local = [0]
        def expect(condition):
            require(condition, 'Synthetic '+name)
            local[0] += 1
        check(expect)
        assertion_count += local[0]
        cases.append({'name': name, 'status': 'passed', 'assertions': local[0]})
    def series(values, **kwargs):
        return [fixture(c, index=i, **kwargs) for i, c in enumerate(values)]
    base = series([100+i%3 for i in range(45)])
    rows, exact = replay(base)
    case('zero_seed_first_row', lambda e: (e(rows[0]['obv'] == 0.0), e(rows[0]['signed_volume'] is None), e(rows[0]['direction'] is None), e(rows[0]['mfm'] == 0.0)))
    tied, _ = replay(series([100, 100], high=110, low=90, volume=100))
    case('equal_close_zero_OBV_nonzero_MFV_possible', lambda e: (e(tied[1]['signed_volume_int'] == 0), e(tied[1]['obv_int'] == 0)))
    particular, _ = replay([fixture(105, high=110, low=90, volume=100), fixture(105, high=110, low=90, volume=100, index=1)])
    case('equal_close_positive_MFV', lambda e: (e(particular[1]['direction'] == 0), e(particular[1]['mfm'] == .5), e(particular[1]['mfv'] == 50.0), e(particular[1]['obv'] == 0.0)))
    up, _ = replay([fixture(90), fixture(95, high=110, low=90, volume=100, index=1)])
    case('up_close_lower_range', lambda e: (e(up[1]['signed_volume'] == 100.0), e(up[1]['mfm'] == -.5), e(up[1]['mfv'] == -50.0)))
    down, _ = replay([fixture(110), fixture(105, high=110, low=90, volume=100, index=1)])
    case('down_close_upper_range', lambda e: (e(down[1]['signed_volume'] == -100.0), e(down[1]['mfm'] == .5), e(down[1]['mfv'] == 50.0)))
    case('CMF_first_twenty_prices', lambda e: (e(rows[18]['cmf'] is None), e(rows[19]['cmf'] is not None), e(rows[19]['window_bars'] == 20)))
    case('matched_OBV_needs_twenty_one_prices', lambda e: (e(rows[19]['obv_change20'] is None), e(rows[20]['obv_change20'] is not None), e(rows[20]['obv_change20_int'] == rows[20]['obv_int']-rows[0]['obv_int'])))
    zero_range, _ = replay(series([100]*21, high=100, low=100, volume=10))
    case('zero_range_retains_denominator', lambda e: (e(zero_range[19]['window_volume'] == 200.0), e(zero_range[19]['window_mfv'] == 0.0), e(zero_range[19]['cmf'] == 0.0)))
    zero_volume, _ = replay(series([100+i for i in range(21)], volume=0))
    case('zero_window_volume_is_unavailable', lambda e: (e(zero_volume[19]['cmf'] is None), e(zero_volume[19]['window_volume'] == 0.0), e(zero_volume[20]['obv_balance20'] is None), e(zero_volume[20]['obv_change20'] == 0.0)))
    variable = [fixture(100+i%2, volume=i+1, index=i) for i in range(23)]
    varied, _ = replay(variable)
    case('current_inclusive_rolling_denominator', lambda e: (e(varied[19]['window_volume'] == sum(range(1,21))), e(varied[20]['window_volume'] == sum(range(2,22)))))
    case('outgoing_signed_volume_removed', lambda e: e(varied[21]['obv_change20_int'] == sum(varied[i]['signed_volume_int'] for i in range(2,22))))
    weighting = [fixture(105 if i%2==0 else 95, high=110, low=90,
                         volume=10 if i==19 else 1, index=i) for i in range(20)]
    weighted, _ = replay(weighting)
    case('volume_weights_change_CMF_without_price_change', lambda e: (e(weighted[19]['window_mfv'] == -4.5),
        e(weighted[19]['window_volume'] == 29.0), e(weighted[19]['cmf_num'] == -9), e(weighted[19]['cmf_den'] == 58)))
    outgoing = [fixture(105 if i==0 else 100, high=110, low=90, volume=10, index=i) for i in range(21)]
    outgoing_rows, _ = replay(outgoing)
    case('outgoing_MFV_term_leaves_fixed_twenty_window', lambda e: (e(outgoing_rows[19]['window_mfv'] == 5.0),
        e(outgoing_rows[19]['cmf'] == .025), e(outgoing_rows[20]['window_mfv'] == 0.0), e(outgoing_rows[20]['cmf'] == 0.0)))
    upper_lower = [fixture(100+i,high=115+i,low=95+i,index=i) for i in range(26)]
    rising_negative,_ = replay(upper_lower)
    case('same_window_OBV_positive_CMF_negative', lambda e: (e(rising_negative[25]['obv_change20'] == 200.0),
        e(rising_negative[25]['obv_balance20'] == 1.0), e(rising_negative[25]['cmf'] == -.5)))
    lower_upper = [fixture(200-i,high=205-i,low=185-i,index=i) for i in range(26)]
    falling_positive,_ = replay(lower_upper)
    case('same_window_OBV_negative_CMF_positive', lambda e: (e(falling_positive[25]['obv_change20'] == -200.0),
        e(falling_positive[25]['obv_balance20'] == -1.0), e(falling_positive[25]['cmf'] == .5)))
    scale_vol = [dict(b, volume=b['volume']*7) for b in base]
    scaled_volume, _ = replay(scale_vol)
    case('positive_common_volume_scaling', lambda e: (e(all(s['obv_int'] == 7*r['obv_int'] for r,s in zip(rows,scaled_volume))), e(all(s['cmf'] == r['cmf'] and s['obv_balance20'] == r['obv_balance20'] for r,s in zip(rows,scaled_volume)))))
    shift_price = [dict(b, **{k: b[k]+1000 for k in ('open','high','low','close')}) for b in base]
    shifted, _ = replay(shift_price)
    case('additive_price_shift_invariance', lambda e: e(all(all(s[k] == r[k] for k in ('obv_int','mfm_num','mfm_den','cmf_num','cmf_den','obv_balance20_num','obv_balance20_den')) for r,s in zip(rows,shifted))))
    scale_price = [dict(b, **{k: b[k]*11 for k in ('open','high','low','close')}) for b in base]
    scaled, _ = replay(scale_price)
    case('positive_price_scale_invariance', lambda e: e(all(s['obv_int'] == r['obv_int'] and s['mfm_num'] == r['mfm_num'] and s['mfm_den'] == r['mfm_den'] and s['cmf'] == r['cmf'] for r,s in zip(rows,scaled))))
    changed_open = [dict(b, open=b['high']) for b in base]
    opened, _ = replay(changed_open)
    case('candle_open_not_direction_input', lambda e: e(all(s['direction'] == r['direction'] and s['mfv'] == r['mfv'] for r,s in zip(rows,opened))))
    one_zero = copy.deepcopy(variable);one_zero[10]['volume']=0
    single_zero, _ = replay(one_zero)
    case('genuine_zero_volume_keeps_price_predecessor', lambda e: (e(single_zero[10]['canonical_run'] == 11), e(single_zero[10]['signed_volume_int'] == 0), e(single_zero[11]['previous_close'] == single_zero[10]['close'])))
    gap = [fixture(100+i, index=i+(1 if i>=22 else 0)) for i in range(45)]
    gaps, _ = replay(gap)
    case('gap_resets_OBV_and_warmup', lambda e: (e(gaps[22]['obv_int'] == 0), e(gaps[22]['direction'] is None), e(gaps[22]['canonical_run'] == 1), e(gaps[40]['cmf'] is None), e(gaps[41]['cmf'] is not None), e(gaps[42]['obv_change20'] is not None)))
    invalid_label = [fixture(100+i, index=i, canonical=i!=22) for i in range(46)]
    labels, _ = replay(invalid_label)
    case('noncanonical_row_unavailable_then_new_segment', lambda e: (e(labels[22]['canonical'] is False), e(all(labels[22][k] is None for k in STATE)), e(labels[23]['obv'] == 0.0), e(labels[23]['canonical_run'] == 1), e(labels[41]['cmf'] is None), e(labels[42]['cmf'] is not None), e(labels[43]['obv_change20'] is not None)))
    micro, _ = replay(series([100, 101, 102], scale=1000000))
    case('millisecond_and_microsecond_close_labels', lambda e: (e(all(b['canonical'] for b in micro)), e(micro[2]['canonical_run'] == 3)))
    edge, _ = replay([fixture(100, high=110,low=90),fixture(110,high=110,low=90,index=1),fixture(90,high=110,low=90,index=2)])
    case('exact_high_low_multiplier_endpoints', lambda e: (e(edge[1]['mfm'] == 1.0), e(edge[2]['mfm'] == -1.0)))
    tiny, _ = replay([fixture(100, volume=.00000001),fixture(100.00000001,index=1,volume=.00000001)])
    case('exact_source_quantum_direction', lambda e: (e(tiny[1]['direction'] == 1), e(tiny[1]['signed_volume_int'] == 1)))
    def rejected(name, modify):
        def check(e):
            altered=copy.deepcopy(base);modify(altered)
            try:replay(altered)
            except (VerificationError, KeyError):e(True)
            else:e(False)
        case(name,check)
    rejected('reject_missing_volume', lambda b:b[2].pop('volume'))
    rejected('reject_negative_volume', lambda b:b[2].update(volume=-1))
    rejected('reject_nonfinite_volume', lambda b:b[2].update(volume=float('nan')))
    rejected('reject_boolean_volume', lambda b:b[2].update(volume=True))
    rejected('reject_nonrepresentable_volume', lambda b:b[2].update(volume=.000000001))
    rejected('reject_close_outside_range', lambda b:b[2].update(close=500))
    rejected('reject_reversed_range', lambda b:b[2].update(high=1))
    rejected('reject_nonpositive_price', lambda b:b[2].update(low=0))
    rejected('reject_duplicate_anchor', lambda b:b[2].update(ts=b[1]['ts']))
    rejected('reject_off_grid_anchor', lambda b:b[2].update(ts=b[2]['ts']+1))
    rejected('reject_timestamp_scale', lambda b:b[2].update(timestamp_scale=1))
    rejected('reject_noninteger_close_label', lambda b:b[2].update(source_close_raw=1.5))
    return {'cases': len(cases), 'passed': len(cases), 'failed': 0, 'assertions': assertion_count, 'results': cases}


def verify(args, report):
    protocol = read(args.protocol)
    require(checksum(args.protocol) == PINNED_PROTOCOL, 'Frozen protocol SHA mismatch')
    require(checksum(args.source_evidence) == PINNED_SOURCE == protocol['source_sha256'], 'Pinned source SHA mismatch')
    require(protocol['period'] == PERIOD and protocol['bar_seconds'] == INTERVAL and protocol['price_scale'] == protocol['volume_scale'] == SCALE, 'Protocol constants')
    source = read(args.source_evidence)
    raw = [{k: row[k] for k in RAW} for row in source['bars']]
    rows, precise = replay(raw)
    evidence = read(args.evidence)
    require(set(evidence) == {'protocol','protocol_sha256','data_quality','bars','examples','teaching','performance_calculated'}, 'Top-level evidence schema')
    compare(evidence['protocol'], protocol, 'protocol', report)
    compare(evidence['protocol_sha256'], PINNED_PROTOCOL, 'protocol_sha256', report)
    compare(evidence['bars'], rows, 'bars', report)
    expected_examples, counts = select(rows, precise, protocol)
    compare(evidence['examples'], expected_examples, 'examples', report)
    compare(evidence['teaching'], protocol['teaching'], 'teaching', report)
    compare(evidence['performance_calculated'], False, 'performance_calculated', report)
    report['teaching'] = verify_teaching(protocol['teaching'])
    report['synthetic'] = synthetic_checks()
    report['series'] = {'rows': len(rows), 'source_fields_compared': len(rows)*len(RAW),
                        'state_fields_compared': len(rows)*(len(rows[0])-len(RAW)),
                        'defined_obv': sum(r['obv'] is not None for r in rows),
                        'defined_cmf': sum(r['cmf'] is not None for r in rows),
                        'defined_obv_balance20': sum(r['obv_balance20'] is not None for r in rows)}
    report['selection'] = {'indices': {e['tag']:e['index'] for e in expected_examples},
                           'eligible_counts': counts, 'all_chart_rows_compared': 93, 'reference_index':25}
    quality = {'rows': len(rows), 'archives': len(source['data_quality']['sources']),
                        'missing_bars': sum((b['ts']-a['ts'])//INTERVAL-1 for a,b in zip(rows,rows[1:])),
                        'noncanonical_rows': sum(not r['canonical'] for r in rows),
                        'segments': sum(r['canonical_run']==1 for r in rows),
                        'zero_volume_rows':sum(r['volume_int']==0 for r in rows),
                        'zero_range_rows':sum(r['high_int']==r['low_int'] for r in rows),
                        'equal_close_comparisons':sum(r['direction']==0 for r in rows),
                        'defined_cmf':sum(r['cmf'] is not None for r in rows),
                        'defined_obv':sum(r['obv'] is not None for r in rows),
                        'defined_obv_balance20':sum(r['obv_balance20'] is not None for r in rows),
                        'empty_volume_windows':sum(r['window_volume_int']==0 for r in rows),
                        'first_ts':rows[0]['ts'],'last_ts':rows[-1]['ts']}
    compare(evidence['data_quality'],quality,'data_quality',report)
    report['source_quality'] = quality
    report['hashes'] = {'protocol_sha256':checksum(args.protocol), 'source_evidence_sha256':checksum(args.source_evidence),
                        'evidence_sha256':checksum(args.evidence),'checker_sha256':checksum(__file__)}
    report['scope'] = {'production_code_read_or_imported':False, 'source_fields_consumed':list(RAW),
                        'strategy_indicators_consumed':False, 'original_archives_replayed':False,
                        'arithmetic':'Independent integer volumes, direct Fraction twenty-bar sums and exact float serialization comparisons.',
                        'performance_calculated':False}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    for name in ('protocol','source-evidence','evidence','report'):
        parser.add_argument('--'+name,required=True,type=Path)
    args=parser.parse_args()
    report={'status':'running','checker':'independent OBV/CMF20 exact-rational verifier','scalar_comparisons':0,'failures':[]}
    try:
        verify(args,report)
        report['status']='passed';code=0
    except (VerificationError,OSError,ValueError,TypeError,KeyError,IndexError,OverflowError,InvalidOperation) as error:
        report['status']='failed';report['failures'].append(str(error));code=1
    args.report.parent.mkdir(parents=True,exist_ok=True)
    args.report.write_text(json.dumps(report,ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
    print(json.dumps({'status':report['status'],'report':str(args.report),'failures':report['failures']},ensure_ascii=False))
    return code


if __name__=='__main__':
    raise SystemExit(main())
