#!/usr/bin/env python3
"""Independent SAR guide verifier; stdlib only, no production-script imports.

Trust boundary: frozen protocol + pinned previously published H4 source evidence.
This checker does not replay the original M1 ZIP archives or reuse their strategy
indicator columns. It copies only the twelve explicitly frozen source columns.
"""
from __future__ import annotations

import argparse
from copy import deepcopy
from fractions import Fraction as F
from hashlib import sha256
import json
import math
from pathlib import Path
import sys

FROZEN_PROTOCOL_SHA = '3e40d762db6d80d57683d817bb11948ec61a0d9f39bceb9a4b6d90d162a5cfdc'
FROZEN_SOURCE_SHA = '29858fbed84e573a6dbe348c8631bef451dfba6bb481ba49b09075c6a6de5973'
FROZEN_MANIFEST_SHA = '9e88e3526802762c68887cc4ca2f05cd60c667fb9886177b4fa5c0773767cd37'
SOURCE_FIELDS = ('ts', 'open', 'high', 'low', 'close', 'n', 'first_ts', 'last_ts',
                 'source_open_int', 'source_high_int', 'source_low_int', 'source_close_int')
STATE_FIELDS = ('incoming_sar', 'direction_before', 'ep_before', 'af_before', 'sar',
                'direction_after', 'ep', 'af', 'reversal', 'ep_updated', 'raw_next',
                'next_sar', 'clamp_applied')
REAL_FIELDS = ('incoming_sar', 'ep_before', 'af_before', 'sar', 'ep', 'af', 'raw_next', 'next_sar')
DIRECTION_FIELDS = ('direction_before', 'direction_after')
FLAG_FIELDS = ('reversal', 'ep_updated', 'clamp_applied')
BAR_FIELDS = set(SOURCE_FIELDS) | {'complete_minute_bucket'} | set(STATE_FIELDS)
TOP_FIELDS = {'protocol', 'protocol_sha256', 'data_quality', 'bars', 'examples', 'teaching', 'performance_calculated'}
EXAMPLE_FIELDS = {'tag', 'index', 'signal_ts', 'available_ts', 'reference_index', 'signal_values', 'previous_values', 'bars'}
A, STEP, CAP = F(1, 50), F(1, 50), F(1, 5)


class VerificationError(Exception):
    pass


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


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


def no_duplicates(pairs):
    obj = {}
    for key, value in pairs:
        need(key not in obj, f'JSON duplicate key: {key}')
        obj[key] = value
    return obj


def load(path):
    def reject_constant(value):
        raise VerificationError(f'Nonfinite JSON constant: {value}')
    return json.loads(Path(path).read_text(encoding='utf-8'),
                      object_pairs_hook=no_duplicates, parse_constant=reject_constant)


def same(actual, expected, where, counter=None):
    """Recursive comparison, including booleans versus 0/1 and exact float type."""
    need(type(actual) is type(expected),
         f'{where}: type {type(actual).__name__}, expected {type(expected).__name__}')
    if isinstance(expected, dict):
        need(set(actual) == set(expected),
             f'{where}: keys differ (missing={sorted(set(expected)-set(actual))}, extra={sorted(set(actual)-set(expected))})')
        for key in expected:
            same(actual[key], expected[key], f'{where}.{key}', counter)
    elif isinstance(expected, list):
        need(len(actual) == len(expected), f'{where}: length {len(actual)}, expected {len(expected)}')
        for i, (left, right) in enumerate(zip(actual, expected)):
            same(left, right, f'{where}[{i}]', counter)
    else:
        if isinstance(actual, float):
            need(math.isfinite(actual), f'{where}: nonfinite value')
        need(actual == expected, f'{where}: {actual!r}, expected {expected!r}')
        if counter is not None:
            counter['scalar_comparisons'] = counter.get('scalar_comparisons', 0) + 1


def fraction(value):
    # Decimal fixture literals are mathematical decimals, not binary float inputs.
    return value if isinstance(value, F) else F(str(value))


def transition(incoming, direction, ep, af, previous_high, previous_low,
               high, low, start=A, step=STEP, cap=CAP):
    """Independent mathematical transition, entirely in rational arithmetic."""
    need(direction in (-1, 1), 'transition: invalid direction')
    incoming, ep, af = map(fraction, (incoming, ep, af))
    ph, pl, high, low = map(fraction, (previous_high, previous_low, high, low))
    need(ph >= pl and high >= low, 'transition: invalid high/low')
    prior_direction, prior_ep, prior_af = direction, ep, af
    hit = low <= incoming if direction == 1 else high >= incoming
    extended = False
    if hit:
        direction *= -1
        emitted = max(ep, ph, high) if direction == -1 else min(ep, pl, low)
        ep = low if direction == -1 else high
        af = start
    else:
        emitted = incoming
        new_extreme = high if direction == 1 else low
        if (new_extreme > ep if direction == 1 else new_extreme < ep):
            ep = new_extreme
            af = min(af + step, cap)
            extended = True
    projected = emitted + af * (ep - emitted)
    following = min(projected, pl, low) if direction == 1 else max(projected, ph, high)
    return {
        'incoming_sar': incoming, 'direction_before': prior_direction,
        'ep_before': prior_ep, 'af_before': prior_af, 'sar': emitted,
        'direction_after': direction, 'ep': ep, 'af': af, 'reversal': hit,
        'ep_updated': extended, 'raw_next': projected, 'next_sar': following,
        'clamp_applied': following != projected,
    }


def public_state(state):
    return {key: float(state[key]) if key in REAL_FIELDS and state[key] is not None else state[key]
            for key in STATE_FIELDS}


def replay(highs, lows):
    need(len(highs) == len(lows), 'replay: unequal input lengths')
    if not highs:
        return []
    highs, lows = list(map(fraction, highs)), list(map(fraction, lows))
    need(all(h >= l for h, l in zip(highs, lows)), 'replay: invalid high/low')
    states = [{key: None for key in STATE_FIELDS}]
    if len(highs) == 1:
        return states
    downward, upward = lows[0] - lows[1], highs[1] - highs[0]
    direction = -1 if downward > 0 and downward > upward else 1
    incoming = lows[0] if direction == 1 else highs[0]
    ep = highs[1] if direction == 1 else lows[1]
    af = A
    for i in range(1, len(highs)):
        previous = i if i == 1 else i - 1
        result = transition(incoming, direction, ep, af, highs[previous], lows[previous], highs[i], lows[i])
        states.append(result)
        incoming, direction, ep, af = (result[key] for key in ('next_sar', 'direction_after', 'ep', 'af'))
    return states


def complete(row, seconds=14400):
    return (row['n'] == seconds // 60 and row['first_ts'] == row['ts']
            and row['last_ts'] == row['ts'] + seconds - 60)


def synthetic_checks():
    results = []
    def check(name, predicate, assertions=1):
        need(predicate, f'synthetic.{name}: failed')
        results.append({'id': name, 'passed': True, 'assertions': assertions})
    def selected(name, state, expected):
        expected = {k: fraction(v) if k in REAL_FIELDS else v for k, v in expected.items()}
        check(name, all(state[k] == v and type(state[k]) is type(v) for k, v in expected.items()), len(expected))
    up = replay([10, 11, 12], [8, 9, 10])
    check('no_first_output', all(v is None for v in up[0].values()), 13)
    selected('startup_up_duplicate_clamp', up[1], {'sar': 8, 'ep': 11, 'af': '.02', 'next_sar': '8.06', 'direction_after': 1, 'ep_updated': False})
    selected('startup_second_output_index', up[2], {'sar': '8.06', 'raw_next': '8.2176'})
    down = replay([10, 9, 8], [8, 7, 6])
    selected('startup_down', down[1], {'sar': 10, 'ep': 7, 'af': '.02', 'next_sar': '9.94', 'direction_after': -1})
    inside = replay([10, 9], [8, '8.5'])[1]
    selected('initial_current_ep_not_two_bar_extreme', inside, {'ep': 9, 'sar': 8, 'next_sar': '8.02'})
    tied = replay([10, 11], [8, 7])[1]
    selected('initial_dm_tie_then_immediate_reversal', tied, {'direction_before': 1, 'direction_after': -1, 'reversal': True, 'sar': 11, 'next_sar': 11})
    point = replay([100]*4, [100]*4)
    check('flat_point_equality_alternation', [s['direction_after'] for s in point[1:]] == [-1, 1, -1]
          and all(s['sar'] == 100 for s in point[1:]), 6)
    ranged = replay([10]*4, [8]*4)
    check('unchanged_nonzero_ranges_alternate', [s['sar'] for s in ranged[1:]] == [10, 8, 10], 3)
    selected('long_exact_contact', transition(100, 1, 110, '.10', 109, 101, 108, 100),
             {'sar': 110, 'direction_after': -1, 'reversal': True, 'ep': 100, 'af': '.02', 'next_sar': '109.8', 'ep_updated': False})
    selected('short_exact_contact', transition(110, -1, 100, '.10', 109, 101, 110, 102),
             {'sar': 100, 'direction_after': 1, 'reversal': True, 'ep': 110, 'af': '.02', 'next_sar': '100.2', 'ep_updated': False})
    selected('long_just_above_contact', transition(100, 1, 110, '.10', 109, 101, 108, '100.000001'), {'reversal': False, 'sar': 100})
    selected('short_just_below_contact', transition(110, -1, 100, '.10', 109, 101, '109.999999', 102), {'reversal': False, 'sar': 110})
    selected('strict_long_ep_tie', transition(100, 1, 110, '.04', 110, 104, 110, 105),
             {'ep_updated': False, 'af': '.04', 'raw_next': '100.4'})
    selected('strict_short_ep_tie', transition(120, -1, 110, '.04', 116, 110, 115, 110),
             {'ep_updated': False, 'af': '.04', 'raw_next': '119.6'})
    selected('new_ep_and_af_affect_next_not_output', transition(100, 1, 110, '.04', 110, 104, 112, 105),
             {'sar': 100, 'ep': 112, 'af': '.06', 'raw_next': '100.72'})
    selected('previous_low_clamp', transition(100, 1, 120, '.20', 120, 101, 119, 105),
             {'raw_next': 104, 'next_sar': 101, 'clamp_applied': True})
    selected('current_low_clamp', transition(100, 1, 120, '.20', 120, 105, 119, 101),
             {'raw_next': 104, 'next_sar': 101, 'clamp_applied': True})
    selected('previous_high_clamp', transition(120, -1, 100, '.20', 119, 100, 115, 101),
             {'raw_next': 116, 'next_sar': 119, 'clamp_applied': True})
    selected('current_high_clamp', transition(120, -1, 100, '.20', 115, 100, 119, 101),
             {'raw_next': 116, 'next_sar': 119, 'clamp_applied': True})
    selected('outside_bar_single_reversal_and_override', transition(100, 1, 110, '.10', 109, 101, 115, 99),
             {'direction_after': -1, 'sar': 115, 'ep': 99, 'af': '.02', 'ep_updated': False, 'raw_next': '114.68', 'next_sar': 115})
    selected('projection_before_test_trap', transition(100, 1, 110, '.04', 110, 103, 112, '100.5'),
             {'reversal': False, 'sar': 100, 'ep': 112, 'af': '.06', 'raw_next': '100.72', 'next_sar': '100.5'})
    first_cap = transition(100, 1, 120, '.18', 119, 110, 121, 111)
    selected('cap_reached_exactly', first_cap, {'af': '.20', 'next_sar': '104.2'})
    second_cap = transition(first_cap['next_sar'], 1, first_cap['ep'], first_cap['af'], 121, 111, 122, 112)
    selected('cap_held_on_new_extreme', second_cap, {'af': '.20', 'ep_updated': True, 'next_sar': '107.76'})
    selected('unrounded_noncontact', transition('100.0004', 1, 110, '.04', 110, 104, 109, '100.001'), {'reversal': False})
    selected('unrounded_contact', transition('100.0004', 1, 110, '.04', 110, 104, 109, 100), {'reversal': True})
    extended = replay([10, 11, 12, 8, 7, 15], [8, 9, 10, 6, 5, 4])
    check('future_append_prefix_causality', extended[:3] == up, 3*13)
    transformed = replay([3*x+1000 for x in [10, 11, 12]], [3*x+1000 for x in [8, 9, 10]])
    price_fields = ('incoming_sar', 'ep_before', 'sar', 'ep', 'raw_next', 'next_sar')
    check('affine_price_units', all(transformed[i][key] == 3*up[i][key]+1000 for i in (1, 2) for key in price_fields)
          and all(transformed[i]['af'] == up[i]['af'] and transformed[i]['direction_after'] == up[i]['direction_after'] for i in (1, 2)), 16)
    restarted = replay([11, 12], [9, 10])
    check('visible_slice_restart_is_not_history', restarted[1]['sar'] != up[2]['sar'], 1)
    check('empty_and_single_observation', replay([], []) == [] and all(v is None for v in replay([10], [8])[0].values()), 14)
    selected('short_new_extreme_updates_next', transition(120, -1, 110, '.04', 116, 110, 115, 108),
             {'sar': 120, 'ep': 108, 'af': '.06', 'raw_next': '119.28', 'next_sar': '119.28'})
    selected('short_outside_bar_single_reversal', transition(120, -1, 110, '.10', 119, 111, 121, 105),
             {'direction_after': 1, 'sar': 105, 'ep': 121, 'af': '.02', 'ep_updated': False, 'raw_next': '105.32', 'next_sar': 105})
    selected('clamp_flag_false_when_bound_equals_projection', transition(100, 1, 110, '.10', 110, 101, 110, 105),
             {'raw_next': 101, 'next_sar': 101, 'clamp_applied': False})
    return results


def build_teaching(protocol):
    expected = deepcopy(protocol['teaching'])
    for name in ('projection', 'touch'):
        group = expected[name]
        direction = group['direction_before']
        initial_af = F(group['af_before_num'], group['af_before_den'])
        for case in group['cases']:
            previous_low = case.get('previous_low', group.get('previous_low'))
            # The projection fixture omits previous_high because its no-hit long
            # branch only uses lows. A valid harmless high is its stored EP.
            previous_high = group.get('previous_high', group['ep_before'])
            high = group['current_high']
            low = case.get('current_low', group.get('current_low'))
            state = transition(group['incoming_sar'], direction, group['ep_before'], initial_af,
                               previous_high, previous_low, high, low)
            need(state['af'] == F(case['expected_af_num'], case['expected_af_den']), f'teaching.{name}: frozen AF expectation')
            if name == 'projection':
                need(state['raw_next'] == fraction(case['expected_raw_next']) and state['next_sar'] == fraction(case['expected_next'])
                     and state['clamp_applied'] is case['clamped'], f'teaching.{name}: frozen projection expectation')
            else:
                need(state['reversal'] is case['expected_reversal'] and state['sar'] == fraction(case['expected_sar']),
                     f'teaching.{name}: frozen touch expectation')
            case['calculated'] = public_state(state)
    return expected


def verify(args, report):
    report['hashes'] = {'checker_sha256': digest(__file__), 'protocol_sha256': digest(args.protocol),
                        'source_evidence_sha256': digest(args.source_evidence), 'evidence_sha256': digest(args.evidence)}
    need(report['hashes']['protocol_sha256'] == FROZEN_PROTOCOL_SHA, 'protocol file SHA256 differs from frozen protocol')
    need(report['hashes']['source_evidence_sha256'] == FROZEN_SOURCE_SHA, 'source evidence SHA256 differs from pinned source')
    protocol = load(args.protocol)
    need(protocol['source_sha256'] == FROZEN_SOURCE_SHA and protocol['source_manifest_sha256'] == FROZEN_MANIFEST_SHA,
         'protocol source pins differ')
    need(tuple(protocol['source_fields']) == SOURCE_FIELDS, 'protocol.source_fields: unsupported field contract')
    need(protocol['parameters'] == {'af_start_num': 1, 'af_start_den': 50, 'af_step_num': 1, 'af_step_den': 50, 'af_max_num': 1, 'af_max_den': 5}, 'protocol parameters differ')
    need(protocol['bar_seconds'] == 14400 and protocol['source_price_scale'] == 1000000, 'protocol interval/price scale differs')
    manifest_path = Path(args.source_evidence).parent / protocol['source_manifest']
    report['hashes']['source_manifest_sha256'] = digest(manifest_path)
    need(report['hashes']['source_manifest_sha256'] == FROZEN_MANIFEST_SHA, 'source manifest SHA256 differs')
    manifest = load(manifest_path)
    source = load(args.source_evidence)
    evidence = load(args.evidence)
    need(type(evidence) is dict and set(evidence) == TOP_FIELDS, 'evidence: top-level schema differs')
    same(evidence['protocol'], protocol, 'evidence.protocol', report)
    same(evidence['protocol_sha256'], FROZEN_PROTOCOL_SHA, 'evidence.protocol_sha256', report)
    same(evidence['performance_calculated'], False, 'evidence.performance_calculated', report)
    synthetic = synthetic_checks()
    report['synthetic'] = {'cases': len(synthetic), 'passed': len(synthetic), 'failed': 0,
                           'assertions': sum(x['assertions'] for x in synthetic), 'results': synthetic}
    raw_rows = source['bars']
    need(type(raw_rows) is list and len(raw_rows) >= 2, 'source bars absent or too short')
    rows, highs, lows = [], [], []
    seconds, scale = protocol['bar_seconds'], protocol['source_price_scale']
    previous_ts = None
    for i, original in enumerate(raw_rows):
        need(all(key in original for key in SOURCE_FIELDS), f'source.bars[{i}]: missing frozen field')
        row = {key: original[key] for key in SOURCE_FIELDS}
        for key in ('ts', 'n', 'first_ts', 'last_ts', 'source_open_int', 'source_high_int', 'source_low_int', 'source_close_int'):
            need(type(row[key]) is int, f'source.bars[{i}].{key}: noninteger')
        need(row['ts'] % seconds == 0 and (previous_ts is None or row['ts'] > previous_ts), f'source.bars[{i}]: anchor order')
        need(previous_ts is None or (row['ts']-previous_ts) % seconds == 0, f'source.bars[{i}]: nonscheduled spacing')
        need(1 <= row['n'] <= seconds//60 and row['ts'] <= row['first_ts'] <= row['last_ts'] < row['ts']+seconds,
             f'source.bars[{i}]: invalid coverage interval')
        need(row['first_ts'] % 60 == row['last_ts'] % 60 == 0, f'source.bars[{i}]: nonminute labels')
        for key in ('open', 'high', 'low', 'close'):
            value = F(row['source_'+key+'_int'], scale)
            need(type(row[key]) in (int, float) and type(row[key]) is not bool and math.isfinite(row[key])
                 and row[key] == float(value), f'source.bars[{i}].{key}: scaled integer mismatch')
        need(row['source_low_int'] <= min(row['source_open_int'], row['source_close_int'])
             <= max(row['source_open_int'], row['source_close_int']) <= row['source_high_int'], f'source.bars[{i}]: OHLC range')
        row['complete_minute_bucket'] = complete(row, seconds)
        rows.append(row)
        highs.append(F(row['source_high_int'], scale)); lows.append(F(row['source_low_int'], scale))
        previous_ts = row['ts']
    states = replay(highs, lows)
    expected_bars = [dict(row, **public_state(state)) for row, state in zip(rows, states)]
    need(type(evidence['bars']) is list and len(evidence['bars']) == len(expected_bars), 'evidence.bars: row count differs')
    for i, (actual, expected) in enumerate(zip(evidence['bars'], expected_bars)):
        need(type(actual) is dict and set(actual) == BAR_FIELDS, f'evidence.bars[{i}]: schema differs')
        same(actual, expected, f'evidence.bars[{i}]', report)
    report['series'] = {'rows': len(rows), 'source_field_comparisons': len(rows)*len(SOURCE_FIELDS),
                        'state_field_comparisons': len(rows)*len(STATE_FIELDS), 'null_initial_state_fields': len(STATE_FIELDS),
                        'exact_serialized_float_comparisons': (len(rows)-1)*len(REAL_FIELDS),
                        'direction_integer_comparisons': (len(rows)-1)*len(DIRECTION_FIELDS),
                        'boolean_state_comparisons': (len(rows)-1)*len(FLAG_FIELDS),
                        'boolean_coverage_comparisons': len(rows), 'maximum_serialized_float_difference': 0.0}
    quality = {'h4_bars': len(rows), 'partial_h4_bars': sum(row['n'] != seconds//60 for row in rows),
               'incomplete_h4_bars': sum(not row['complete_minute_bucket'] for row in rows),
               'calendar_gaps': sum(b['ts']-a['ts'] != seconds for a, b in zip(rows, rows[1:])),
               'first_ts': rows[0]['ts'], 'last_ts': rows[-1]['ts'], 'source_files': len(manifest['files']),
               'defined_sar': len(rows)-1, 'reversals': sum(s['reversal'] is True for s in states),
               'clamped_next_levels': sum(s['clamp_applied'] is True for s in states),
               'capped_af_rows': sum(s['af'] == CAP for s in states)}
    same(evidence['data_quality'], quality, 'evidence.data_quality', report)
    report['data_quality'] = quality
    selection = protocol['selection']; before, after = selection['chart_previous'], selection['chart_following']
    need((before, after, selection['reference_index']) == (25, 5, 25), 'protocol chart shape differs')
    predicates = {
        'up_reversal': lambda s, r: s['direction_before'] == -1 and s['reversal'] and s['direction_after'] == 1,
        'wick_reversal': lambda s, r: s['direction_before'] == 1 and s['reversal'] and F(r['source_close_int'], scale) > s['incoming_sar'],
        'af_cap': lambda s, r: not s['reversal'] and s['ep_updated'] and s['af_before'] == CAP and s['af'] == CAP,
    }
    chosen, expected_examples, counts = set(), [], {}
    for tag in selection['order']:
        need(tag in predicates, 'protocol selection predicate unsupported')
        eligible = []
        for i in range(before, len(rows)-after):
            row = rows[i]
            if row['ts'] < selection['start_ts'] or i in chosen:
                continue
            if row['ts']-rows[i-1]['ts'] != seconds or not row['complete_minute_bucket'] or not rows[i-1]['complete_minute_bucket']:
                continue
            if predicates[tag](states[i], row):
                eligible.append(i)
        need(eligible, f'selection.{tag}: no eligible case')
        index = eligible[0]; chosen.add(index); counts[tag] = len(eligible)
        expected_examples.append({'tag': tag, 'index': index, 'signal_ts': rows[index]['ts'],
                                  'available_ts': rows[index]['ts']+seconds, 'reference_index': before,
                                  'signal_values': expected_bars[index], 'previous_values': expected_bars[index-1],
                                  'bars': expected_bars[index-before:index+after+1]})
    for i, actual in enumerate(evidence['examples']):
        need(type(actual) is dict and set(actual) == EXAMPLE_FIELDS, f'evidence.examples[{i}]: schema differs')
    same(evidence['examples'], expected_examples, 'evidence.examples', report)
    report['selection'] = {'examples': len(expected_examples), 'chart_rows_compared': sum(len(x['bars']) for x in expected_examples),
                           'snapshot_rows_compared': 2*len(expected_examples), 'reference_index': before,
                           'selected_indices': {x['tag']: x['index'] for x in expected_examples},
                           'eligible_counts_at_each_ordered_selection': counts}
    teaching = build_teaching(protocol)
    same(evidence['teaching'], teaching, 'evidence.teaching', report)
    report['teaching'] = {'figures': 2, 'cases': sum(len(teaching[g]['cases']) for g in ('projection', 'touch')),
                          'state_fields_compared': sum(len(teaching[g]['cases'])*len(STATE_FIELDS) for g in ('projection', 'touch')),
                          'copied_fixture_metadata_matches_protocol': True}
    report['scope'] = {'production_code_read_or_imported': False, 'other_strategy_indicators_consumed': False,
                       'original_archives_replayed': False, 'source_boundary': 'Pinned previously published H4 evidence; only twelve frozen raw-price/coverage fields consumed.',
                       'arithmetic': 'Exact Fraction, then exact float(Fraction) comparison; no numerical tolerance for state values or branches.',
                       'history': 'One replay from first observed source row; no calendar-gap or partial-bucket reset.',
                       'performance_calculated': False}
    report['checks_passed'] = ['frozen_protocol_sha256', 'pinned_source_sha256', 'pinned_manifest_sha256',
                               'embedded_protocol', 'top_level_schema', 'retained_source_fields', 'scaled_integer_prices',
                               'all_state_fields_exact', 'strict_types_and_flags', 'full_observed_history', 'coverage_and_quality',
                               'first_eligible_distinct_selection', 'all_example_snapshots_and_chart_rows', 'all_teaching_cases',
                               'independent_synthetic_boundaries', 'no_performance_calculation']


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--protocol', required=True, type=Path)
    parser.add_argument('--source-evidence', required=True, type=Path)
    parser.add_argument('--evidence', required=True, type=Path)
    parser.add_argument('--report', required=True, type=Path)
    args = parser.parse_args()
    report = {'status': 'running', 'checker': 'independent SAR exact-rational verifier',
              'scalar_comparisons': 0, 'failures': []}
    try:
        verify(args, report)
        report['status'] = 'passed'
        code = 0
    except (VerificationError, OSError, ValueError, TypeError, KeyError, IndexError, OverflowError) 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())
