#!/usr/bin/env python3
"""Independent Williams %R14 / raw Stochastic guide checker, stdlib only.

Uses monotonic extrema queues, gcd-reduced integer ratios and raw-K integer
comparisons for flags. Does not import or execute the production engine or use
source strategy indicators. The previously published H4 input JSON is pinned;
original ZIP reconstruction and account profitability are outside this audit.
"""
from __future__ import annotations
import argparse
from collections import Counter, deque
from copy import deepcopy
from datetime import datetime, timezone
from decimal import Decimal, localcontext
import hashlib
import json
from math import gcd
from pathlib import Path
import sys

PROTOCOL_SHA='3bf65c70f998363ebc9c89c676a4af8839c3e0de972c70145cc6de5f35a46f6f'
SOURCE_SHA='060f24b65562a768dde311f7e6ff09ba69c4bc99c2c2457e46dd7b2bc95b88ad'
STEP=14400;SCALE=100000000;N=14
BASE=('ts','open','high','low','close','volume','source_close_raw','timestamp_scale','canonical')
INT_FIELDS=tuple('source_'+k+'_int'for k in ('open','high','low','close'))
NUMERIC=('low14','high14','wr','raw_k','wr_numerator','wr_denominator','raw_k_numerator','raw_k_denominator')
FLAGS=('low_cross','low_zone','high_zone','rising_below')
ALL_FIELDS=BASE+INT_FIELDS+NUMERIC+FLAGS
FIELD_CATEGORIES=('source_input_fields','integer_price_fields','oscillator_and_extrema_fields','discrete_flags')
MISSING=object()

class AuditError(Exception):pass

class Audit:
    def __init__(self):self.counts=Counter();self.failures=[];self.failure_count=0
    def check(self,ok,category,label,actual=MISSING,expected=MISSING):
        self.counts[category]+=1
        if not ok:
            self.failure_count+=1
            if len(self.failures)<30:
                f={'check':label,'category':category}
                if actual is not MISSING:f['actual']=repr(actual)[:300]
                if expected is not MISSING:f['expected']=repr(expected)[:300]
                self.failures.append(f)
        return bool(ok)
    def same(self,actual,expected,category,label):return self.check(equal(actual,expected),category,label,actual,expected)
    def require(self,ok,category,label):
        if not self.check(ok,category,label):raise AuditError(label)

def equal(actual,expected):
    if isinstance(expected,dict):return isinstance(actual,dict)and set(actual)==set(expected)and all(equal(actual[k],v)for k,v in expected.items())
    if isinstance(expected,list):return isinstance(actual,list)and len(actual)==len(expected)and all(equal(a,b)for a,b in zip(actual,expected))
    if type(expected)is int:return type(actual)is int and actual==expected
    if type(expected)is bool:return type(actual)is bool and actual==expected
    if expected is None:return actual is None
    if isinstance(expected,Decimal):return type(actual)in(int,Decimal)and Decimal(actual)==expected
    return type(actual)is type(expected)and actual==expected

def strict_json(path):
    blob=Path(path).read_bytes()
    def constant(value):raise AuditError('Nonfinite JSON constant: '+value)
    def pairs(items):
        result={}
        for key,value in items:
            if key in result:raise AuditError('Duplicate JSON key: '+key)
            result[key]=value
        return result
    return json.loads(blob,parse_float=Decimal,parse_constant=constant,object_pairs_hook=pairs),hashlib.sha256(blob).hexdigest()

def reduced(n,d):
    if d<=0:raise AuditError('Ratio denominator must be positive')
    g=gcd(abs(n),d);return n//g,d//g

def displayed(pair):
    if pair is None:return None
    # Independent decimal reconstruction of the nearest serialized binary64.
    # No Fraction.__float__ call is shared with the production implementation.
    with localcontext()as ctx:
        ctx.prec=80
        return Decimal(str(float(Decimal(pair[0])/Decimal(pair[1]))))

def canonical(b):return b['source_close_raw']==(b['ts']+STEP)*b['timestamp_scale']-1

def normalize(source,a):
    out=[]
    a.require(isinstance(source,list)and bool(source),'source_schema','nonempty source bars array')
    for i,b in enumerate(source):
        a.require(isinstance(b,dict)and all(k in b for k in BASE),'source_schema',f'source row {i} base fields')
        for k in ('ts','source_close_raw','timestamp_scale'):a.require(type(b[k])is int,'source_schema',f'source row {i}.{k} integer')
        a.require(type(b['canonical'])is bool and b['timestamp_scale']in(1000,1000000),'source_schema',f'source row {i} metadata types')
        a.same(b['canonical'],canonical(b),'source_canonical_boundary',f'source row {i} close boundary alignment')
        a.require(b['ts']%STEP==0 and(not i or b['ts']>out[-1]['ts']and(b['ts']-out[-1]['ts'])%STEP==0),
                  'source_chronology',f'source row {i} chronological H4 anchor')
        row={k:b[k]for k in BASE};p={}
        for k in ('open','high','low','close'):
            value=b[k]
            a.require(type(value)in(int,Decimal),'source_schema',f'source row {i}.{k} finite number')
            scaled=Decimal(value)*SCALE
            a.require(scaled==scaled.to_integral_value(),'source_precision',f'source row {i}.{k} exact 1e-8 units')
            p[k]=int(scaled);row['source_'+k+'_int']=p[k]
            if k!='open':a.same(b.get(k+'_int',MISSING),p[k],'source_published_HLC_ints',f'source row {i}.{k}_int')
        a.require(0<p['low']<=min(p['open'],p['close'])<=max(p['open'],p['close'])<=p['high'],
                  'source_OHLC_validity',f'source row {i} OHLC bounds')
        a.require(type(b['volume'])in(int,Decimal)and b['volume']>=0,'source_OHLC_validity',f'source row {i} volume')
        out.append(row)
    return out

def calculate(integer_rows):
    highest=deque();lowest=deque();run=0;out=[];state=[]
    for i,b in enumerate(integer_rows):
        adjacent=i>0 and b['ts']-integer_rows[i-1]['ts']==STEP;good=canonical(b)
        if not adjacent or not good:highest.clear();lowest.clear();run=0
        lo=hi=wp=kp=None
        if good:
            run+=1;h,l,c=(b['source_'+k+'_int']for k in ('high','low','close'))
            while highest and highest[-1][1]<=h:highest.pop()
            while lowest and lowest[-1][1]>=l:lowest.pop()
            highest.append((i,h));lowest.append((i,l));first=i-(N-1)
            while highest and highest[0][0]<first:highest.popleft()
            while lowest and lowest[0][0]<first:lowest.popleft()
            if run>=N:
                hi=highest[0][1];lo=lowest[0][1];width=hi-lo
                if width>0:wp=reduced(-100*(hi-c),width);kp=reduced(100*(c-lo),width)
        previous=state[-1]['kp']if state else None;pair=adjacent and kp is not None and previous is not None
        lower=None if kp is None else kp[0]<20*kp[1];upper=None if kp is None else kp[0]>80*kp[1]
        cross=bool(pair and previous[0]<=20*previous[1]and kp[0]>20*kp[1])
        rising=bool(pair and kp[0]*previous[1]>previous[0]*kp[1]and kp[0]<20*kp[1])
        r=dict(b)
        r.update(low14=None if lo is None else Decimal(lo)/SCALE,high14=None if hi is None else Decimal(hi)/SCALE,
                 wr=displayed(wp),raw_k=displayed(kp),wr_numerator=None if wp is None else wp[0],
                 wr_denominator=None if wp is None else wp[1],raw_k_numerator=None if kp is None else kp[0],
                 raw_k_denominator=None if kp is None else kp[1],low_cross=cross,low_zone=lower,high_zone=upper,rising_below=rising)
        out.append(r);state.append({'wp':wp,'kp':kp,'canonical_run':run,'adjacent':adjacent})
    return out,state

def select(rows,state,protocol):
    candidates={key:[]for key in ('low_cross','low_zone','high_run')}
    for i,b in enumerate(rows):
        if b['ts']<protocol['selection']['start_ts']or i<25 or i+5>=len(rows)or state[i]['canonical_run']<17:continue
        if b['low_cross']:candidates['low_cross'].append(i)
        if b['rising_below']:candidates['low_zone'].append(i)
        if all(rows[j]['high_zone']is True for j in range(i-3,i+1)):candidates['high_run'].append(i)
    used=set();picked={}
    for tag in protocol['selection']['order']:
        index=next((i for i in candidates[tag]if i not in used),None)
        if index is None:raise AuditError('No qualifying example: '+tag)
        used.add(index);picked[tag]=index
    return picked,{key:len(v)for key,v in candidates.items()}

def compare_row(a,actual,expected,label):
    if not a.check(isinstance(actual,dict),'payload_structure',label+' object'):return
    a.same(set(actual),set(ALL_FIELDS),'payload_structure',label+' exact field set')
    for field in BASE:a.same(actual.get(field,MISSING),expected[field],'source_input_fields',label+'.'+field)
    for field in INT_FIELDS:a.same(actual.get(field,MISSING),expected[field],'integer_price_fields',label+'.'+field)
    for field in NUMERIC:a.same(actual.get(field,MISSING),expected[field],'oscillator_and_extrema_fields',label+'.'+field)
    for field in FLAGS:a.same(actual.get(field,MISSING),expected[field],'discrete_flags',label+'.'+field)
    if expected['wr']is not None:
        parts=[actual.get(k)for k in ('wr_numerator','wr_denominator','raw_k_numerator','raw_k_denominator')]
        ok=all(type(v)is int for v in parts)and parts[1]>0 and parts[3]>0
        if ok:wn,wd,kn,kd=parts;ok=wn*kd+100*wd*kd==kn*wd
        a.check(ok,'exact_published_identity',label+' WR = rawK - 100 from published integer fractions')

def quality(rows,source):
    gaps=[]
    for i in range(1,len(rows)):
        if rows[i]['ts']-rows[i-1]['ts']>STEP:gaps.append({'left':rows[i-1]['ts'],'right':rows[i]['ts'],'missing':(rows[i]['ts']-rows[i-1]['ts'])//STEP-1})
    return {'rows':len(rows),'source_files':len(source['data_quality']['sources']),'gaps':gaps,
            'missing_bars':sum(g['missing']for g in gaps),'noncanonical_closes':[b['ts']for b in rows if not canonical(b)],
            'timestamp_units':dict(Counter(str(b['timestamp_scale'])for b in rows)),'first_ts':rows[0]['ts'],
            'last_ts':rows[-1]['ts'],'defined_readings':sum(b['wr']is not None for b in rows)}

def expected_teaching():
    table=[{'low':100,'high':110,'close':c,'raw_k':100*(c-100)//10,'wr':-100*(110-c)//10}for c in(100,102,105,108,110)]
    sequence=[10,50,90];mean=sum(sequence)//len(sequence)
    return {'range_table':table,'smoothing':{'raw_k_sequence':sequence,'latest_raw_k':sequence[-1],
            'latest_wr':sequence[-1]-100,'slow_k':mean,'slow_shifted':mean-100},
            'flat':{'low':100,'high':100,'close':100,'raw_k':None,'wr':None}}

def fixture(prices,scale=1000):
    start=1577836800;rows=[]
    for i,(h,l,c)in enumerate(prices):
        values={k:int(Decimal(str(v))*SCALE)for k,v in [('open',c),('high',h),('low',l),('close',c)]};ts=start+i*STEP
        b={'ts':ts,'open':Decimal(values['open'])/SCALE,'high':Decimal(values['high'])/SCALE,
           'low':Decimal(values['low'])/SCALE,'close':Decimal(values['close'])/SCALE,'volume':0,
           'source_close_raw':(ts+STEP)*scale-1,'timestamp_scale':scale,'canonical':True}
        b.update({'source_'+k+'_int':v for k,v in values.items()});rows.append(b)
    return rows

def edge_cases(a,input_rows,protocol):
    results=[]
    def record(name,ok,detail):
        a.check(ok,'edge_case_scenarios',name);results.append({'name':name,'passed':bool(ok),'detail':detail})
    f=fixture([(200,100,110)]*13+[(200,100,120),(200,100,121)]);r,s=calculate(f)
    record('warmup_13_14_and_threshold_cross15',all(x['wr']is None for x in r[:13])and s[13]['wp']==(-80,1)
           and not r[13]['low_cross']and s[14]['wp']==(-79,1)and r[14]['low_cross'],
           'First 13 null; observation14=-80 is not a cross; observation15=-79 crosses from previous equality.')
    f=fixture([(200,100,120)]*14+[(200,100,120),(200,100,Decimal('120.00000001'))]);r,s=calculate(f)
    record('exact_lower_equality_and_rounded_label',not r[13]['low_zone']and not r[14]['low_cross']
           and r[15]['low_cross']and format(r[15]['wr'],'.2f')=='-80.00',
           'Current equality fails, previous equality qualifies; one tick above -80 displays -80.00 but crosses exactly.')
    f=fixture([(200,100,180)]*14+[(200,100,Decimal('179.99999999')),(200,100,Decimal('180.00000001'))]);r,s=calculate(f)
    record('exact_upper_equality_and_rounding',not r[13]['high_zone']and not r[14]['high_zone']and r[15]['high_zone']
           and format(r[14]['wr'],'.2f')==format(r[15]['wr'],'.2f')=='-20.00',
           'Exactly -20 is outside strict upper zone; distinct one-tick readings can both display -20.00.')
    f=fixture([(100,100,100)]*14+[(110,100,110),(110,100,101),(110,100,103)]);r,s=calculate(f)
    record('flat_null_recovery_without_history_reset_or_bridge',r[13]['low14']==r[13]['high14']==100
           and r[13]['wr']is None and r[13]['raw_k']is None and r[13]['low_zone']is None
           and s[14]['wp']==(0,1)and s[14]['canonical_run']==15 and not r[14]['low_cross']and r[16]['low_cross'],
           'Flat 0/0 stays null; next positive range is immediately defined, but cannot cross from a null predecessor.')
    f=fixture([(200,100,130)]*29)
    for b in f[14:]:b['ts']+=STEP;b['source_close_raw']+=STEP*b['timestamp_scale']
    r,s=calculate(f)
    record('missing_H4_restarts_before_current_canonical_row',r[13]['wr']is not None
           and all(x['wr']is None for x in r[14:27])and r[27]['wr']is not None and s[14]['canonical_run']==1,
           'Gap starts a new segment; 13 new observations are null and the 14th can be defined.')
    f=fixture([(200,100,130)]*29,1000000);f[14]['source_close_raw']-=1;f[14]['canonical']=False;r,s=calculate(f)
    record('microsecond_noncanonical_row_retained_and_restart',len(r)==29 and r[14]['wr']is None
           and s[14]['canonical_run']==0 and all(x['wr']is None for x in r[15:28])and r[28]['wr']is not None,
           'Noncanonical microsecond close remains a row without indicators; next canonical row starts at one.')
    f=fixture([(300,90,200),(250,100,150)]+[(200,110,150)]*11+[(250,100,150),(200,110,150)]);r,s=calculate(f)
    record('equal_extrema_and_rolling_eviction',r[13]['high14']==300 and r[13]['low14']==90
           and r[14]['high14']==250 and r[14]['low14']==100 and s[14]['wp']==(-200,3),
           'An older extreme expires; repeated remaining equal extrema preserve the proper range value.')
    f=fixture([(300,100,121)]+[(200,100,121)]*14);r,s=calculate(f)
    record('fixed_close_changing_range_can_cross',r[13]['close']==r[14]['close']and s[13]['wp']==(-179,2)
           and s[14]['wp']==(-79,1)and r[14]['low_cross'],
           'Unchanged close crosses -80 when the expired high changes the rolling denominator.')
    f=fixture([(200,100,110)]*14+[(200,100,190)]);r,s=calculate(f)
    record('full_jump_over_upper_has_no_cap',s[13]['wp']==(-90,1)and s[14]['wp']==(-10,1)
           and r[14]['low_cross']and r[14]['high_zone'],
           'Jump -90 to -10 is a valid recovery cross; older strategy ceiling must not leak into this guide.')
    f=fixture([(200,100,105)]*14+[(200,100,115),(200,100,115)]);r,s=calculate(f)
    record('rising_below_is_separate_from_recovery',r[14]['rising_below']and r[14]['low_zone']
           and not r[14]['low_cross']and not r[15]['rising_below'],
           '-95 to -85 rises inside lower zone; equal successive readings are not rising.')
    seq=[10,50,90];wrseq=[x-100 for x in seq]
    record('linear_smoothing_preserves_matching_shift_but_not_raw_comparison',
           sum(wrseq)/3==sum(seq)/3-100 and wrseq[-1]!=sum(seq)/3-100,
           'Identical SMA shifts commute; latest raw WR=-10 differs from smoothed rawK-100=-50.')
    f=fixture([(200,100,120)]*30);base,base_s=calculate(f);transformed=deepcopy(f)
    for b in transformed:
        for k in INT_FIELDS:b[k]=7*b[k]+500*SCALE
    tr,tr_s=calculate(transformed)
    record('positive_affine_price_scaling_preserves_ratios',all(x['wp']==y['wp']and x['kp']==y['kp']for x,y in zip(base_s,tr_s)),
           'Multiplying every price by seven and adding the same constant leaves normalized positions unchanged.')
    full,full_s=calculate(input_rows);picked,_=select(full,full_s,protocol)
    cuts=tuple(sorted({13,14,15,25,26,*[i+1 for i in picked.values()]}));prefix_ok=True
    for cut in cuts:
        part,part_s=calculate(input_rows[:cut]);prefix_ok=prefix_ok and equal(part,full[:cut])and equal(part_s,full_s[:cut])
    record('prefix_independence',prefix_ok,f'{len(cuts)} source prefixes compared, including warmup and independently selected-example boundaries.')
    future_ok=True
    for tag,i in picked.items():
        mutated=deepcopy(input_rows)
        for b in mutated[i+1:]:
            b['source_high_int']=100000*SCALE;b['source_low_int']=SCALE;b['source_open_int']=b['source_close_int']=50000*SCALE
        single=deepcopy(protocol);single['selection']['order']=[tag]
        changed,changed_s=calculate(mutated);new_picked,_=select(changed,changed_s,single)
        future_ok=future_ok and new_picked[tag]==i and equal(changed[:i+1],full[:i+1])
    record('future_prices_do_not_select_current_example',future_ok,
           'All later HLC values changed separately after each selected candle; its first-match index and prefix stayed identical.')
    return results

def run(args,a,report):
    protocol,psha=strict_json(args.protocol);source,ssha=strict_json(args.source_evidence);evidence,esha=strict_json(args.evidence)
    report.update(protocol_sha256=psha,source_sha256=ssha,evidence_sha256=esha)
    a.require(psha==PROTOCOL_SHA,'hash_pins','exact recovery-frozen protocol SHA256')
    a.require(ssha==SOURCE_SHA,'hash_pins','exact pinned source SHA256')
    a.same(protocol.get('source_sha256'),SOURCE_SHA,'hash_pins','protocol source pin')
    a.same(protocol.get('period'),N,'protocol_contract','period14');a.same(protocol.get('window_observations'),N,'protocol_contract','14 observations')
    a.same(protocol.get('source_price_scale'),SCALE,'protocol_contract','integer price scale')
    a.same(protocol.get('source_manifest'),source['data_quality']['sources'],'source_manifest','all79 source manifest entries')
    a.same(evidence.get('protocol'),protocol,'embedded_provenance','embedded protocol')
    a.same(evidence.get('protocol_sha256'),psha,'embedded_provenance','embedded protocol SHA256')
    a.same(evidence.get('performance_calculated'),False,'embedded_provenance','no performance calculation')
    a.require(set(evidence)=={'protocol','protocol_sha256','data_quality','bars','examples','teaching','performance_calculated'},
              'payload_structure','exact evidence top-level schema')
    inputs=normalize(source['bars'],a);rows,state=calculate(inputs);observed=evidence['bars']
    a.require(isinstance(observed,list),'payload_structure','evidence bars list');a.same(len(observed),len(rows),'payload_structure','all source bars retained')
    for i,(actual,expected)in enumerate(zip(observed,rows)):compare_row(a,actual,expected,f'bars[{i}]')
    main_fields=sum(a.counts[k]for k in FIELD_CATEGORIES);q=quality(rows,source)
    a.same(evidence['data_quality'],q,'quality','complete recomputed quality object');teach=expected_teaching()
    a.same(protocol['teaching'],teach,'teaching','protocol toy arithmetic and smoothing');a.same(evidence['teaching'],teach,'teaching','evidence toy arithmetic and smoothing')
    picked,counts=select(rows,state,protocol);examples=evidence['examples']
    a.require(isinstance(examples,list),'payload_structure','examples list');a.same([c.get('tag')for c in examples],list(picked),'example_selection','exact unique case order')
    cases={}
    for example,(tag,i)in zip(examples,picked.items()):
        label='examples.'+tag
        a.same(set(example),{'tag','index','signal_ts','available_ts','reference_index','signal_values','previous_values','bars'},'payload_structure',label+' exact fields')
        for k,v in {'tag':tag,'index':i,'signal_ts':rows[i]['ts'],'available_ts':rows[i]['ts']+STEP,'reference_index':25}.items():a.same(example.get(k,MISSING),v,'example_selection',label+'.'+k)
        compare_row(a,example.get('signal_values'),rows[i],label+'.signal_values');compare_row(a,example.get('previous_values'),rows[i-1],label+'.previous_values')
        context=example.get('bars');a.require(isinstance(context,list),'payload_structure',label+' context list');a.same(len(context),31,'example_context',label+' 25+1+5 context count')
        for j,(actual,expected)in enumerate(zip(context,rows[i-25:i+6])):compare_row(a,actual,expected,f'{label}.bars[{j}]')
        cases[tag]={'index':i,'opening_ts':rows[i]['ts'],'available_ts':rows[i]['ts']+STEP,
                    'available_utc':datetime.fromtimestamp(rows[i]['ts']+STEP,timezone.utc).isoformat(),
                    'wr_fraction':state[i]['wp'],'raw_k_fraction':state[i]['kp'],'wr':str(rows[i]['wr']),
                    'raw_k':str(rows[i]['raw_k']),'context_indices':[i-25,i+5],'canonical_rows_required':17}
    report.update(bar_count=len(rows),defined_pair_count=q['defined_readings'],null_pair_count=len(rows)-q['defined_readings'],
                  input_OHLC_integer_values=len(rows)*4,quality=q,candidate_counts=counts,selected_cases=cases,
                  unique_historical_windows_with_exact_identity=q['defined_readings'],main_bar_scalar_field_comparisons=main_fields,
                  example_copy_scalar_field_comparisons=sum(a.counts[k]for k in FIELD_CATEGORIES)-main_fields,
                  exact_cross_count=sum(b['low_cross']for b in rows),rising_below_count=sum(b['rising_below']for b in rows),
                  strict_lower_zone_count=sum(b['low_zone']is True for b in rows),strict_upper_zone_count=sum(b['high_zone']is True for b in rows))
    report['edge_cases']=edge_cases(a,inputs,protocol)

def main():
    ap=argparse.ArgumentParser(description=__doc__)
    for key in ('protocol','source-evidence','evidence','report'):ap.add_argument('--'+key,type=Path,required=True)
    args=ap.parse_args()
    if args.report.resolve()in{p.resolve()for p in(args.protocol,args.source_evidence,args.evidence)}:raise SystemExit('Report path must differ from inputs')
    a=Audit();report={'checker':'williams-guide-independent-integer-queues-recovery-v1',
        'method':'Monotonic extrema queues; gcd-reduced integer ratios; raw-K integer comparisons for flags; no production imports.',
        'scope':'Pinned H4 input JSON, guide payload copies, exact arithmetic/flags, first-match selection, teaching and synthetic edge cases. Original ZIPs and account returns are not audited here.',
        'counting_note':'check_count sums performed validations by category, including source types/precision and copied example fields. It is not a count of unique observations or independent experiments. Each named synthetic scenario counts once.',
        'checker_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        'files':{k:str(getattr(args,k))for k in('protocol','source_evidence','evidence')}}
    try:run(args,a,report)
    except Exception as exc:
        if not isinstance(exc,AuditError)or not a.failure_count:a.check(False,'malformed_or_execution',str(exc))
        report['exception']=type(exc).__name__+': '+str(exc)
    report.update(status='passed'if not a.failure_count else'failed',checks=dict(sorted(a.counts.items())),
                  check_count=sum(a.counts.values()),failure_count=a.failure_count,failures=a.failures)
    args.report.parent.mkdir(parents=True,exist_ok=True);args.report.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps({k:report[k]for k in('status','check_count','failure_count')}))
    if a.failures:print(json.dumps(a.failures[:5],ensure_ascii=False),file=sys.stderr)
    return int(bool(a.failure_count))

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