#!/usr/bin/env python3
"""Independent MFI14 evidence checker: stdlib, exact price-unit Fraction windows.

No production replay imports. Every output window is freshly summed from14
explicit TP*base-volume comparisons rather than maintained/cancelled integer sums.
"""
import argparse
import collections
import hashlib
import json
import math
import sys
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from pathlib import Path

PROTOCOL_SHA = '386e62ccb0f6901b755eb4106a5938dd5ec048757bbd3d2e686ec8a3080cbea3'
SOURCE_SHA = '060f24b65562a768dde311f7e6ff09ba69c4bc99c2c2457e46dd7b2bc95b88ad'
BASE = ('ts','open','high','low','close','volume','source_close_raw','timestamp_scale')
DERIVED = ('canonical','open_int','high_int','low_int','close_int','volume_int',
 'tp_sum_int','typical_price','raw_flow','direction','positive_flow','negative_flow',
 'positive_sum','negative_sum','positive_sum_num','negative_sum_num','mfi','mfi_num',
 'mfi_den','canonical_run','cross_20_up','upper_zone','lower_zone')
FIELDS = BASE + DERIVED
TOP = {'protocol','protocol_sha256','data_quality','bars','examples','teaching','performance_calculated'}

class AuditError(Exception):
    pass

class Audit:
    def __init__(self):
        self.counts = collections.Counter()
        self.edges = []
    def require(self, condition, label, group='structure'):
        self.counts[group] += 1
        if not condition:
            raise AuditError(label)
    def equal(self, actual, expected, label, group='payload'):
        if isinstance(expected, dict):
            self.require(isinstance(actual, dict), label+': object required', group)
            self.require(set(actual) == set(expected), label+': keys differ', group)
            for key, value in expected.items():
                self.equal(actual[key], value, label+'.'+str(key), group)
        elif isinstance(expected, list):
            self.require(isinstance(actual, list), label+': array required', group)
            self.require(len(actual)==len(expected), label+': array length differs', group)
            for i, (a, e) in enumerate(zip(actual, expected)):
                self.equal(a, e, label+'['+str(i)+']', group)
        elif isinstance(expected, bool):
            self.require(type(actual) is bool and actual is expected, label+': boolean differs', group)
        elif expected is None:
            self.require(actual is None, label+': expected null', group)
        elif isinstance(expected, int):
            self.require(type(actual) is int and actual==expected, label+': integer differs', group)
        elif isinstance(expected, Decimal):
            self.require(type(actual) in (int, Decimal) and actual==expected,
                         label+': numeric output differs', group)
        else:
            self.require(type(actual) is type(expected) and actual==expected,
                         label+': value differs', group)


def read_json(path):
    def invalid_constant(value):
        raise AuditError('Nonfinite JSON constant: '+value)
    try:
        return json.loads(Path(path).read_text(), parse_float=Decimal,
                          parse_constant=invalid_constant)
    except (OSError, ValueError) as error:
        raise AuditError('Cannot read JSON '+str(path)+': '+str(error)) from error


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


def number(value, field):
    if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
        raise AuditError(field+': finite number required')
    try:
        dec = value if isinstance(value, Decimal) else Decimal(str(value))
    except (InvalidOperation, ValueError) as error:
        raise AuditError(field+': invalid decimal') from error
    if not dec.is_finite():
        raise AuditError(field+': nonfinite number')
    return dec


def integer_units(value, scale, field):
    exact = Fraction(number(value, field))*scale
    if exact.denominator != 1:
        raise AuditError(field+': not representable at source precision')
    return exact.numerator


def published(value):
    """Exact mathematical value rounded once to the evidence binary64 format."""
    return None if value is None else Decimal(repr(float(value)))


def input_rows(rows, price_scale, volume_scale, seconds):
    if not isinstance(rows, list) or not rows:
        raise AuditError('Nonempty source bar array required')
    clean=[]
    for index, row in enumerate(rows):
        if not isinstance(row, dict) or any(field not in row for field in BASE):
            raise AuditError('Source row missing required field at '+str(index))
        for field in ('ts','source_close_raw','timestamp_scale'):
            if type(row[field]) is not int:
                raise AuditError('Source '+field+' must be integer at '+str(index))
        ts=row['ts']; scale=row['timestamp_scale']
        if scale not in (1000,1000000) or ts % seconds:
            raise AuditError('Invalid timestamp scale/anchor at '+str(index))
        if clean and (ts<=clean[-1]['ts'] or (ts-clean[-1]['ts']) % seconds):
            raise AuditError('Source anchors not strictly scheduled at '+str(index))
        values={field:Fraction(number(row[field],field)) for field in ('open','high','low','close','volume')}
        if any(values[field]<=0 for field in ('open','high','low','close')):
            raise AuditError('Nonpositive price at '+str(index))
        if not (values['low']<=min(values['open'],values['close']) and
                values['high']>=max(values['open'],values['close']) and
                values['low']<=values['high']):
            raise AuditError('Invalid OHLC bounds at '+str(index))
        if values['volume']<0:
            raise AuditError('Negative source volume at '+str(index))
        ints={field:integer_units(row[field],volume_scale if field=='volume' else price_scale,field)
              for field in ('open','high','low','close','volume')}
        tp=(values['high']+values['low']+values['close'])/3
        clean.append(dict(ts=ts, canonical=row['source_close_raw']==(ts+seconds)*scale-1,
                          values=values, ints=ints, tp=tp,
                          raw=tp*values['volume'], base={k:row[k] for k in BASE}))
    return clean


def ratio(positive,negative):
    if positive<0 or negative<0:
        raise AuditError('Flow sums must be nonnegative')
    return 100*positive/(positive+negative) if positive+negative else None


def flags(previous,current,adjacent=True):
    return {'cross_20_up':bool(adjacent and previous is not None and current is not None and
                              previous<=20 and current>20),
            'upper_zone':None if current is None else current>80,
            'lower_zone':None if current is None else current<20}


def rebuild(rows,price_scale=100000000,volume_scale=100000000,seconds=14400,period=14):
    clean=input_rows(rows,price_scale,volume_scale,seconds)
    output=[]; exact=[]; run=0
    for i, row in enumerate(clean):
        joined=bool(i and row['canonical'] and clean[i-1]['canonical'] and
                    row['ts']-clean[i-1]['ts']==seconds)
        run=(run+1 if joined else 1) if row['canonical'] else 0
        direction=None
        positive=negative=None
        if joined:
            direction=(row['tp']>clean[i-1]['tp'])-(row['tp']<clean[i-1]['tp'])
            positive=row['raw'] if direction>0 else Fraction(0)
            negative=row['raw'] if direction<0 else Fraction(0)
        p=n=mfi=None
        if run>=period+1:
            # Fresh direct pairwise sum in real quote units, independent of a
            # rolling integer buffer or cancellation of its common divisor.
            window=clean[i-period:i+1]
            p=sum((current['tp']*current['values']['volume']
                   for previous,current in zip(window,window[1:])
                   if current['tp']>previous['tp']),Fraction(0))
            n=sum((current['tp']*current['values']['volume']
                   for previous,current in zip(window,window[1:])
                   if current['tp']<previous['tp']),Fraction(0))
            mfi=ratio(p,n)
        item=dict(row['base'])
        item.update(canonical=row['canonical'],
                    **{field+'_int':value for field,value in row['ints'].items()},
                    tp_sum_int=sum(row['ints'][field] for field in ('high','low','close')),
                    typical_price=published(row['tp']),raw_flow=published(row['raw']),
                    direction=direction,positive_flow=published(positive),negative_flow=published(negative),
                    positive_sum=published(p),negative_sum=published(n),
                    positive_sum_num=None if p is None else int(p*3*price_scale*volume_scale),
                    negative_sum_num=None if n is None else int(n*3*price_scale*volume_scale),
                    mfi=published(mfi),mfi_num=None if mfi is None else mfi.numerator,
                    mfi_den=None if mfi is None else mfi.denominator,canonical_run=run)
        item.update(flags(exact[-1] if exact else None,mfi,joined))
        output.append(item);exact.append(mfi)
    return output,exact,clean


def select_examples(bars,exact,start,order):
    predicates={
      'low_cross':lambda i:bars[i]['cross_20_up'],
      'body_disagrees':lambda i:exact[i] is not None and bars[i]['direction']==1 and
          bars[i]['volume_int']>0 and bars[i]['close_int']<bars[i]['open_int'],
      'high_run':lambda i:i>=2 and all(v is not None and v>80 for v in exact[i-2:i+1])}
    eligible=[i for i in range(25,len(bars)-5)
              if bars[i]['ts']>=start and bars[i]['canonical_run']>=17]
    selected=[]; counts={}
    for tag in order:
        candidates=[i for i in eligible if predicates[tag](i)]
        counts[tag]=len(candidates)
        chosen=next((i for i in candidates if i not in selected),None)
        if chosen is None:
            raise AuditError('No distinct eligible example for '+tag)
        selected.append(chosen)
    result=[]
    for tag,index in zip(order,selected):
        result.append(dict(tag=tag,index=index,signal_ts=bars[index]['ts'],
             available_ts=bars[index]['ts']+14400,reference_index=25,
             signal_values=bars[index],previous_values=bars[index-1],
             bars=bars[index-25:index+6]))
    return result,counts,len(eligible)


def toy_rows(prices,volumes=None):
    if volumes is None: volumes=[1]*len(prices)
    result=[]
    for i,(tp,vol) in enumerate(zip(prices,volumes)):
        tp=Decimal(str(tp));ts=i*14400
        result.append(dict(ts=ts,open=tp,high=tp,low=tp,close=tp,volume=Decimal(str(vol)),
                           source_close_raw=(ts+14400)*1000-1,timestamp_scale=1000))
    return result


def teaching(audit,protocol,actual):
    expected=protocol['synthetic']
    audit.equal(actual,expected,'teaching','teaching')
    weighting=expected['weighting']
    for key,volume_key in [('expected_equal','equal_volumes'),('expected_heavy','heavy_last_volumes')]:
        prices=weighting['typical_prices'];volumes=weighting[volume_key]
        audit.require(len(prices)==15 and len(volumes)==14,
                      'Teaching volumes describe14 comparisons after reference price','teaching')
        bars,values,_=rebuild(toy_rows(prices,[0]+volumes))
        final=bars[-1];record=weighting[key]
        audit.equal(final['positive_sum'],Decimal(record['positive_sum']),'teaching.'+key+'.P','teaching')
        audit.equal(final['negative_sum'],Decimal(record['negative_sum']),'teaching.'+key+'.N','teaching')
        audit.equal(values[-1],Fraction(record['mfi_num'],record['mfi_den']),
                    'teaching.'+key+'.MFI','teaching')
    for key,record in expected['endpoints'].items():
        audit.require(len(record['typical_prices'])==15 and len(record['volumes'])==14,
                      'Endpoint volumes describe14 comparisons after reference price','teaching')
        bars,values,_=rebuild(toy_rows(record['typical_prices'],[0]+record['volumes']))
        audit.equal(bars[-1]['positive_sum'],Decimal(record['positive_sum']),'teaching.'+key+'.P','teaching')
        audit.equal(bars[-1]['negative_sum'],Decimal(record['negative_sum']),'teaching.'+key+'.N','teaching')
        audit.equal(values[-1],None if record['mfi'] is None else Fraction(record['mfi']),
                    'teaching.'+key+'.MFI','teaching')


def edge_cases(a):
    def check(condition,label): a.require(condition,label,'edge_cases')
    def finish(name,start): a.edges.append({'name':name,'status':'passed','checks':a.counts['edge_cases']-start})
    start=a.counts['edge_cases']
    b,v,_=rebuild(toy_rows(range(100,117)))
    check(all(x is None for x in v[:14]),'Warmup must last through price14')
    check(v[14]==100 and b[14]['canonical_run']==15,'First MFI after15 prices')
    finish('Fourteen comparisons require fifteen prices',start)

    start=a.counts['edge_cases']
    rows=toy_rows(list(range(115,100,-1))+[102],[1]*15+[1000]);b,v,_=rebuild(rows)
    check(v[14]==0 and b[15]['cross_20_up'],'Earliest cross on sixteenth price')
    check(not any(x['cross_20_up'] for x in b[:15]),'No warmup cross')
    _,v,_=rebuild(toy_rows(range(100,117)))
    check(not all(x is not None and x>80 for x in v[13:16]),'Three values unavailable at16 prices')
    check(all(x is not None and x>80 for x in v[14:17]),'Three values ready at17 prices')
    finish('Sixteenth-price cross and seventeenth-price three-value run',start)

    start=a.counts['edge_cases']
    epsilon=Fraction(1,10**12)
    check(not flags(Fraction(19),Fraction(20))['cross_20_up'],'Current20 not crossed')
    check(flags(Fraction(20),20+epsilon)['cross_20_up'],'Previous20 included')
    check(flags(Fraction(20),Fraction(100))['cross_20_up'],'Cross has no upper cap')
    check(not flags(20+epsilon,Fraction(30))['cross_20_up'],'Previous above20 excluded')
    check(flags(None,Fraction(100))['cross_20_up'] is False,'No cross from null')
    check(flags(Fraction(0),Fraction(80))['upper_zone'] is False,'Exactly80 outside upper zone')
    check(flags(Fraction(0),Fraction(20))['lower_zone'] is False,'Exactly20 outside lower zone')
    check(round(float(20-epsilon),2)==round(float(20+epsilon),2)==20,'Same rounded boundary display')
    check(flags(20-epsilon,20+epsilon)['cross_20_up'],'Exact fractions decide rounded cross')
    finish('Exact threshold equality, full jumps and rounded boundary',start)

    start=a.counts['edge_cases']
    rows=toy_rows([100]*16,[10**10]*16)
    rows[1].update(high=Decimal(102),low=Decimal(98),close=Decimal(100))
    rows[2].update(high=Decimal(103),low=Decimal(97),close=Decimal(100))
    b,v,_=rebuild(rows)
    check(all(x['direction']==0 for x in b[1:]),'Equal sums mean exact TP tie')
    check(all(x['positive_flow']==x['negative_flow']==0 for x in b[1:]),'Tie volume excluded')
    check(v[-1] is None and b[-1]['positive_sum']==b[-1]['negative_sum']==0,'Tied window undefined')
    finish('Exact equal typical prices with different candles and large volume',start)

    start=a.counts['edge_cases']
    b,_,_=rebuild(toy_rows([100,109,105]+list(range(106,119)),[1,0]+[1]*14))
    check(b[1]['direction']==1 and b[1]['positive_flow']==0,'Zero-volume movement contributes zero')
    check(b[2]['direction']==-1,'Zero-volume price remains predecessor')
    b,v,_=rebuild(toy_rows(range(100,115),[0]*15))
    check(v[-1] is None and b[-1]['canonical_run']==15,'Zero-volume observations remain valid')
    finish('Real zero volume remains a valid predecessor',start)

    start=a.counts['edge_cases']
    _,up,_=rebuild(toy_rows(range(100,115)));_,down,_=rebuild(toy_rows(range(114,99,-1)))
    check(up[-1]==100 and down[-1]==0,'Directional endpoint windows')
    check(ratio(Fraction(5),Fraction(5))==50,'Equal positive magnitudes give50')
    check(ratio(Fraction(0),Fraction(0)) is None,'Empty window stays null')
    check(ratio(Fraction(0),Fraction(3))==0 and ratio(Fraction(3),Fraction(0))==100,'Endpoint algebra')
    finish('Zero, one hundred, fifty and empty-denominator cases',start)

    start=a.counts['edge_cases']
    b,v,_=rebuild(toy_rows([100]+[101]*15+[102]))
    check(v[14]==100 and v[15] is None and v[16]==100,'Empty-window eviction and recovery')
    check(not b[16]['cross_20_up'],'Recovered value cannot bridge unavailable predecessor')
    finish('Empty-flow recovery and no cross over null',start)

    start=a.counts['edge_cases']
    rows=toy_rows(range(100,140))
    for r in rows[15:]:
        r['ts']+=14400;r['source_close_raw']=(r['ts']+14400)*1000-1
    b,v,_=rebuild(rows)
    check(b[15]['canonical_run']==1 and v[28] is None and v[29]==100,'Gap restarts15-price readiness')
    rows=toy_rows(range(100,140));rows[15]['source_close_raw']-=1
    b,v,_=rebuild(rows)
    check(b[15]['canonical_run']==0 and b[16]['canonical_run']==1,'Noncanonical bar resets chain')
    check(v[29] is None and v[30]==100,'Post-noncanonical readiness')
    check(not any(x['cross_20_up'] for x in b[15:31]),'No cross across restarted warmup')
    finish('Missing anchor and noncanonical-close resets',start)

    start=a.counts['edge_cases']
    for label,value in [('missing',None),('negative',-1),('NaN',Decimal('NaN')),
                        ('infinity',Decimal('Infinity')),('precision',Decimal('0.000000001'))]:
        rows=toy_rows([100,101])
        if label=='missing': del rows[1]['volume']
        else: rows[1]['volume']=value
        try: rebuild(rows)
        except AuditError: check(True,'Rejected '+label+' volume')
        else: check(False,'Accepted '+label+' volume')
    rows=toy_rows([100,101]);rows[1]['high']=Decimal(99)
    try: rebuild(rows)
    except AuditError: check(True,'Rejected malformed OHLC')
    else: check(False,'Accepted malformed OHLC')
    finish('Reject absent, negative, nonfinite or unrepresentable volume and invalid OHLC',start)

    start=a.counts['edge_cases']
    prices=[100,110]+[109,110]*6+[109,110]
    b,v,_=rebuild(toy_rows(prices,[1,1000]+[1]*14))
    check(b[-1]['direction']==1 and v[-1]<v[-2],'Positive TP can accompany declining MFI')
    check(b[-1]['positive_sum']<b[-2]['positive_sum'],'Outgoing heavy positive flow matters')
    finish('Rolling eviction can outweigh a new positive flow',start)

    start=a.counts['edge_cases']
    rows=toy_rows(prices,[1,1000]+[1]*14);_,base,_=rebuild(rows)
    shifted=[]
    for row in rows:
        item=dict(row)
        for key in ('open','high','low','close'): item[key]*=3
        item['volume']*=7;shifted.append(item)
    _,scaled,_=rebuild(shifted)
    check(base==scaled,'Positive common price and volume scaling invariance')
    for row in shifted: row['volume']/=7
    _,price_only,_=rebuild(shifted)
    check(base==price_only,'Positive common price scaling invariance')
    finish('Positive common scaling invariance',start)

    start=a.counts['edge_cases']
    prices=[100,101]+[100]*13;_,base,_=rebuild(toy_rows(prices))
    _,shifted,_=rebuild(toy_rows([p+100 for p in prices]))
    check(base[-1]==Fraction(10100,201),'Original shift counterexample')
    check(shifted[-1]==Fraction(20100,401) and base[-1]!=shifted[-1],'Additive shift not invariant')
    finish('Additive price-shift counterexample',start)

    start=a.counts['edge_cases']
    prices=[100,110]+[109]*13;volumes=[1,1,2]+[1]*12
    b,v,_=rebuild(toy_rows(prices,volumes))
    check(b[-1]['positive_sum']==110 and b[-1]['negative_sum']==218,'Raw TP times volume sums')
    check(v[-1]==Fraction(1375,41) and v[-1]!=Fraction(250,3),'Change-weighted calculation differs')
    finish('Wrong change-in-TP times volume counterexample',start)

    start=a.counts['edge_cases']
    rows=toy_rows([100+(i%7) for i in range(50)],[1+i%4 for i in range(50)])
    full,_,_=rebuild(rows);prefix,_,_=rebuild(rows[:31])
    check(full[:31]==prefix,'Prefix independence')
    changed=[dict(row) for row in rows]
    for i in range(31,len(changed)):
        for key in ('open','high','low','close'): changed[i][key]=Decimal(900+i)
        changed[i]['volume']=Decimal(999999)
        changed[i]['source_close_raw']-=1
    amended,_,_=rebuild(changed)
    check(amended[:31]==full[:31],'Future price/volume/quality independence')
    finish('Prefix and future independence',start)


def verify(args,a):
    protocol=read_json(args.protocol);source=read_json(args.source_evidence);evidence=read_json(args.evidence)
    a.equal(digest(args.protocol),PROTOCOL_SHA,'Pinned protocol hash','provenance')
    a.equal(digest(args.source_evidence),SOURCE_SHA,'Pinned original source hash','provenance')
    a.equal(protocol['source_sha256'],SOURCE_SHA,'Protocol source pin','provenance')
    a.require(isinstance(evidence,dict) and set(evidence)==TOP,'Evidence top-level schema','structure')
    a.equal(evidence['protocol'],protocol,'Embedded frozen protocol','provenance')
    a.equal(evidence['protocol_sha256'],PROTOCOL_SHA,'Evidence protocol hash','provenance')
    a.equal(evidence['performance_calculated'],False,'No performance calculated','structure')
    a.equal(protocol['period'],14,'MFI period','structure')
    a.equal(protocol['bar_seconds'],14400,'H4 interval','structure')
    a.equal(protocol['selection']['order'],['low_cross','body_disagrees','high_run'],'Declared selection order','structure')
    a.equal(protocol['selection']['start_ts'],1672531200,'Selection start','structure')
    a.equal(protocol['display']['candles'],31,'Display rows','structure')
    a.equal(protocol['display']['reference_index'],25,'Display reference','structure')
    rows=source.get('bars')
    bars,exact,clean=rebuild(rows,protocol['price_scale'],protocol['volume_scale'],14400,14)
    a.require(isinstance(evidence['bars'],list),'Evidence bar array','structure')
    a.equal(len(evidence['bars']),len(bars),'All source rows retained','structure')
    for i,(actual,expected) in enumerate(zip(evidence['bars'],bars)):
        a.equal(actual,expected,'bars['+str(i)+']','all_bar_fields')
    gaps=[{'left':left['ts'],'right':right['ts'],'missing':(right['ts']-left['ts'])//14400-1}
          for left,right in zip(bars,bars[1:]) if right['ts']-left['ts']!=14400]
    noncanonical=[b['ts'] for b in bars if not b['canonical']]
    source_quality=source['data_quality'];archives=source_quality['sources']
    a.equal(source_quality['rows'],len(bars),'Source quality row count','source_quality')
    a.equal(source_quality['gaps'],gaps,'Recomputed source gaps','source_quality')
    a.equal(source_quality['missing_bars'],sum(g['missing'] for g in gaps),'Source missing rows','source_quality')
    a.equal(source_quality['noncanonical_closes'],noncanonical,'Source noncanonical closes','source_quality')
    a.equal(source_quality['source_files'],len(archives),'Source archive count','source_quality')
    a.require(len({r['file'] for r in archives})==len(archives),'Distinct source archive names','source_quality')
    for record in archives:
        a.require(isinstance(record['sha256'],str) and len(record['sha256'])==64 and
                  all(c in '0123456789abcdef' for c in record['sha256']),
                  'Source archive SHA format','source_quality')
    units=dict(collections.Counter(str(b['timestamp_scale']) for b in bars))
    a.equal(source_quality['timestamp_units'],units,'Source timestamp-unit counts','source_quality')
    quality=dict(rows=len(bars),archives=len(archives),missing_bars=sum(g['missing'] for g in gaps),
                 noncanonical_rows=len(noncanonical),defined_mfi=sum(v is not None for v in exact),
                 undefined_mfi=sum(v is None for v in exact),
                 empty_flow_windows=sum(b['positive_sum']==b['negative_sum']==0
                                        for b in bars if b['positive_sum'] is not None),
                 zero_volume_rows=sum(b['volume_int']==0 for b in bars),
                 first_ts=bars[0]['ts'],last_ts=bars[-1]['ts'])
    a.equal(evidence['data_quality'],quality,'Derived data quality','data_quality')
    examples,candidates,eligible=select_examples(bars,exact,protocol['selection']['start_ts'],protocol['selection']['order'])
    a.equal(evidence['examples'],examples,'Three deterministic examples','examples')
    teaching(a,protocol,evidence['teaching'])
    edge_cases(a)
    return dict(data_quality=quality,selected_indices={e['tag']:e['index'] for e in examples},
                candidate_counts_before_distinct_exclusion=candidates,eligible_indices=eligible,
                exact_field_count_per_row=len(FIELDS),display_rows=sum(len(e['bars']) for e in examples),
                source_gap_count=len(gaps),source_noncanonical_anchors=noncanonical,
                method='Exact Fraction typical price from source Decimal OHLC, multiplied by source Decimal base volume; fresh explicit pairwise sum for every14-comparison window. No production replay imports or integer-cancellation rolling buffer.')


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    for name in ('protocol','source-evidence','evidence','report'): parser.add_argument('--'+name,required=True)
    args=parser.parse_args();a=Audit();report={}
    try:
        report=verify(args,a);status='passed';error=None
    except Exception as exc:
        status='failed';error=type(exc).__name__+': '+str(exc)
    report.update(status=status,failures=[] if error is None else [error],
                  validation_operations=sum(a.counts.values()),operations_by_group=dict(a.counts),
                  operation_count_definition='One scalar comparison or explicit structure/input assertion is one validation operation; this is not a count of independent experiments.',
                  edge_case_scenarios=len(a.edges),edge_cases=a.edges,
                  input_hashes={key:digest(path) for key,path in [('protocol',args.protocol),('source_evidence',args.source_evidence),('evidence',args.evidence)] if Path(path).exists()},
                  independence='Standalone stdlib checker; no production study or builder imported, copied or executed.')
    Path(args.report).write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({key:report[key] for key in ('status','validation_operations','edge_case_scenarios','failures')}))
    return 0 if status=='passed' else 1

if __name__=='__main__':
    sys.exit(main())
