#!/usr/bin/env python3
"""Independent CCI20 guide audit: exact Fraction typical prices and windows.

No production engine is imported or executed. Unlike the production integer
cancellation, this rebuild explicitly forms each (H+L+C)/3, its current-window
mean and every absolute distance from that one mean. Original M1 ZIPs are not
reprocessed; the published H4 source JSON is pinned by SHA-256.
"""
from __future__ import annotations
import argparse
from collections import Counter
from copy import deepcopy
from datetime import datetime,timezone
from decimal import Decimal,localcontext
from fractions import Fraction as F
import hashlib
import json
from pathlib import Path
import sys

PROTOCOL_SHA='cb14cfc36b89a13d6dd748a40e59fbd328ee1bc3db924365bee459e7cea762bd'
SOURCE_SHA='29858fbed84e573a6dbe348c8631bef451dfba6bb481ba49b09075c6a6de5973'
N=20;STEP=14400;SCALE=1000000;CONSTANT=F(3,200)
BASE=('ts','open','high','low','close','n','first_ts','last_ts','source_open_int','source_high_int','source_low_int','source_close_int')
VALUES=('typical_price','mean_tp','mean_abs_dev','deviation','cci','cci_num','cci_den')
FLAGS=('cross_zero_up','cross_100_up','below_minus100','complete_minute_bucket')
FIELDS=BASE+VALUES+FLAGS
MISSING=object()

class AuditError(Exception):pass

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

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:
                item={'check':label,'category':category}
                if actual is not MISSING:item['actual']=repr(actual)[:280]
                if expected is not MISSING:item['expected']=repr(expected)[:280]
                self.failures.append(item)
        return bool(ok)
    def same(self,a,b,category,label):return self.check(equal(a,b),category,label,a,b)
    def require(self,ok,category,label):
        if not self.check(ok,category,label):raise AuditError(label)

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

def export(value):
    if value is None:return None
    with localcontext()as ctx:
        ctx.prec=80
        return Decimal(str(float(Decimal(value.numerator)/Decimal(value.denominator))))

def exact_number(value):
    return value.numerator if value.denominator==1 else Decimal(value.numerator)/Decimal(value.denominator)

def complete(row):return row['n']==240 and row['first_ts']==row['ts']and row['last_ts']==row['ts']+STEP-60

def stats(window):
    mean=sum(window,F(0))/len(window)
    mad=sum((abs(v-mean)for v in window),F(0))/len(window)
    deviation=window[-1]-mean
    return mean,mad,deviation,None if mad==0 else deviation/(CONSTANT*mad)

def crossed(before,now,threshold,adjacent=True):
    return bool(adjacent and before is not None and now is not None and before<=threshold<now)

def normalize(source,a):
    a.require(isinstance(source,list)and bool(source),'source_schema','nonempty source bars')
    rows=[]
    for i,b in enumerate(source):
        a.require(isinstance(b,dict)and all(k in b for k in BASE),'source_schema',f'source[{i}] base fields')
        for key in ('ts','n','first_ts','last_ts','source_open_int','source_high_int','source_low_int','source_close_int'):
            a.require(type(b[key])is int,'source_schema',f'source[{i}].{key} integer')
        a.require(b['ts']%STEP==0 and(not i or b['ts']>rows[-1]['ts']and(b['ts']-rows[-1]['ts'])%STEP==0),
                  'source_chronology',f'source[{i}] ordered H4 anchor')
        a.require(0<b['n']<=240 and b['ts']<=b['first_ts']<=b['last_ts']<b['ts']+STEP
                  and b['first_ts']%60==b['last_ts']%60==0,'source_coverage',f'source[{i}] minute bounds')
        for key in ('open','high','low','close'):
            a.require(type(b[key])in(int,Decimal),'source_schema',f'source[{i}].{key} number')
            a.same(Decimal(b[key])*SCALE,Decimal(b['source_'+key+'_int']),'source_price_integer_consistency',f'source[{i}].{key}')
        a.require(0<b['source_low_int']<=min(b['source_open_int'],b['source_close_int'])
                  <=max(b['source_open_int'],b['source_close_int'])<=b['source_high_int'],
                  'source_OHLC_validity',f'source[{i}] OHLC bounds')
        rows.append({k:b[k]for k in BASE})
    return rows

def calculate(inputs):
    rows=[];typical=[];ratios=[];anchor_runs=[]
    for i,b in enumerate(inputs):
        tp=(F(b['source_high_int'],SCALE)+F(b['source_low_int'],SCALE)+F(b['source_close_int'],SCALE))/3
        typical.append(tp);mean=mad=dev=cci=None
        if i>=N-1:mean,mad,dev,cci=stats(typical[i-N+1:i+1])
        adjacent=i>0 and b['ts']-inputs[i-1]['ts']==STEP
        anchor_runs.append(anchor_runs[-1]+1 if adjacent else 1)
        before=ratios[-1]if ratios else None
        r=dict(b);r.update(typical_price=export(tp),mean_tp=export(mean),mean_abs_dev=export(mad),deviation=export(dev),
            cci=export(cci),cci_num=None if cci is None else cci.numerator,cci_den=None if cci is None else cci.denominator,
            cross_zero_up=crossed(before,cci,F(0),adjacent),cross_100_up=crossed(before,cci,F(100),adjacent),
            below_minus100=None if cci is None else cci<-100,complete_minute_bucket=complete(b))
        rows.append(r);ratios.append(cci)
    return rows,ratios,typical,anchor_runs

def eligible(rows,runs,i):
    return i>=25 and i+5<len(rows)and runs[i]>=22 and complete(rows[i-1])and complete(rows[i])

def select(rows,runs,protocol):
    candidates={key:[]for key in ('zero_cross','upper_cross','lower_run')}
    for i,b in enumerate(rows):
        if b['ts']<protocol['selection']['start_ts']or not eligible(rows,runs,i):continue
        if b['cross_zero_up']:candidates['zero_cross'].append(i)
        if b['cross_100_up']:candidates['upper_cross'].append(i)
        if all(rows[j]['below_minus100']is True for j in range(i-2,i+1)):candidates['lower_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 first qualifying example: '+tag)
        used.add(index);picked[tag]=index
    return picked,{k:len(v)for k,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(FIELDS),'payload_structure',label+' exact fields')
    for key in BASE:a.same(actual.get(key,MISSING),expected[key],'source_input_fields',label+'.'+key)
    for key in VALUES:a.same(actual.get(key,MISSING),expected[key],'derived_value_fields',label+'.'+key)
    for key in FLAGS:a.same(actual.get(key,MISSING),expected[key],'discrete_flag_fields',label+'.'+key)
    if expected['cci']is not None:
        n,d=actual.get('cci_num'),actual.get('cci_den')
        a.check(type(n)is int and type(d)is int and d>0 and abs(F(n,d))<=F(2000,3),
                'fixed_period_bound',label+' exact published fraction within proven bound')

def quality(rows,ratios,source):
    return {'h4_bars':len(rows),'partial_h4_bars':sum(b['n']<240 for b in rows),
            'incomplete_h4_bars':sum(not complete(b)for b in rows),
            'calendar_gaps':sum(rows[i]['ts']-rows[i-1]['ts']!=STEP for i in range(1,len(rows))),
            'first_ts':rows[0]['ts'],'last_ts':rows[-1]['ts'],'source_files':source['data_quality']['source_files'],
            'defined_cci':sum(v is not None for v in ratios),
            'zero_mad_windows':sum(b['mean_abs_dev']==0 for b in rows if b['mean_abs_dev']is not None)}

def teaching():
    mean_window=list(map(F,[100]*10+[110]*9+[120]));m,d,v,c=stats(mean_window)
    bound=list(map(F,[100]*19+[110]));bm,bd,bv,bc=stats(bound)
    prelude=list(map(F,[100]*19));window=list(map(F,[110]*20));series=prelude+window
    residuals=[abs(series[i]-sum(series[i-19:i+1],F(0))/20)for i in range(19,len(series))]
    cm,cd,cv,cc=stats(window);wrong=sum(residuals,F(0))/20
    return {'typical_example':{'high':112,'low':100,'close':109,'typical_price':exact_number(F(112+100+109,3))},
       'mean_window':[int(v)for v in mean_window],
       'mean_example':{'mean_tp':exact_number(m),'mean_abs_dev':exact_number(d),'deviation':exact_number(v),'cci_num':c.numerator,'cci_den':c.denominator},
       'zero_mad_nonflat':{'high':110,'low':90,'close':100,'observations':20,'mean_tp':100,'mean_abs_dev':0,'cci':None},
       'wrong_residual':{'prelude':[int(v)for v in prelude],'window':[int(v)for v in window],
         'correct_mean':exact_number(cm),'correct_mad':exact_number(cd),'correct_cci':cc,'wrong_mad':exact_number(wrong)},
       'bound_example':{'window':[int(v)for v in bound],'mean_tp':exact_number(bm),'mean_abs_dev':exact_number(bd),
                        'deviation':exact_number(bv),'cci_num':bc.numerator,'cci_den':bc.denominator}}

def fixture(values):
    rows=[];start=1577836800
    for i,value in enumerate(values):
        tp=F(value);scaled=tp*SCALE
        if scaled.denominator!=1:raise AuditError('Synthetic TP does not fit integer source scale')
        p=scaled.numerator;ts=start+i*STEP
        rows.append({'ts':ts,'open':Decimal(p)/SCALE,'high':Decimal(p)/SCALE,'low':Decimal(p)/SCALE,
          'close':Decimal(p)/SCALE,'n':240,'first_ts':ts,'last_ts':ts+STEP-60,
          'source_open_int':p,'source_high_int':p,'source_low_int':p,'source_close_int':p})
    return rows

def edge_cases(a,inputs):
    results=[]
    def test(name,ok,detail):
        a.check(ok,'edge_case_scenarios',name);results.append({'name':name,'passed':bool(ok),'detail':detail})
    b=fixture([100])[0];b.update(source_high_int=112*SCALE,source_low_int=100*SCALE,source_close_int=109*SCALE)
    r,q,tp,runs=calculate([b]);test('HLC3_typical_price107',tp==[F(107)],'H112 L100 C109 gives exact TP107; open is not used.')
    t=teaching();test('current_mean_MAD_toy5800_over33',t['mean_example']=={'mean_tp':Decimal('105.5'),'mean_abs_dev':Decimal('5.5'),'deviation':Decimal('14.5'),'cci_num':5800,'cci_den':33},'Ten TP100, nine110 and current120 use one mean105.5 and MAD5.5.')
    test('wrong_rolling_residual_mean475',t['wrong_residual']['correct_mad']==0 and t['wrong_residual']['correct_cci']is None and t['wrong_residual']['wrong_mad']==Decimal('4.75'),'Nineteen100 then twenty110: true final MAD0, wrong historic-center residual average4.75.')
    f=fixture([100]*20+[110,100]);
    for b in f[:20]:b['source_high_int']=110*SCALE;b['source_low_int']=90*SCALE;b['source_close_int']=100*SCALE
    r,q,tp,runs=calculate(f);test('nonflat_constantTP_null_and_recovery_no_bridge',q[19]is None and r[19]['mean_abs_dev']==0 and q[20]is not None and not r[20]['cross_zero_up'],
      'Nonzero candle ranges can have constant TP; next positive MAD is immediately defined but cannot cross from null.')
    test('nonflat_CCI_zero',stats(list(map(F,[90,110]+[100]*18)))==(F(100),F(1),F(0),F(0)),'Current TP equals a nonflat window mean; zero is a valid reading.')
    f=fixture([117,80]+[100]*17+[103,104]);r,q,tp,runs=calculate(f)
    test('readiness20_and_first_cross21',all(v is None for v in q[:19])and q[19]==100 and q[20]>100 and not r[19]['cross_100_up']and r[20]['cross_100_up'],
      'First19 unavailable; twentieth100; twenty-first strictly crosses from previous equality.')
    f=fixture([103,114,80]+[100]*16+[103,103,104]);r,q,tp,runs=calculate(f)
    nq=stats(list(map(F,[200-v for v in [103,114,80]+[100]*16+[103]])))[3]
    test('threshold_equality',q[19]==q[20]==100 and not r[20]['cross_100_up']and r[21]['cross_100_up']and nq==-100 and not(nq<-100),
      'Current equality is not a strict zone/cross; previous equality can precede a fresh cross; exactly-100 is not below-100.')
    cap=stats(list(map(F,[100]*19+[110])))[3];low=stats(list(map(F,[110]*19+[100])))[3]
    test('fixed_period_cap_attained',cap==F(2000,3)and low==-F(2000,3),'Positive and negative windows attain exact +/-2000/3.')
    w=list(map(F,[100]*10+[110]*9+[120]));test('positive_affine_invariance',stats([F(7,3)*v+F(23,5)for v in w])[3]==stats(w)[3],
      'Positive scaling and a common additive price shift cancel from CCI.')
    f=fixture([117,80]+[100]*17+[103,104]);f[-1]['ts']+=STEP;f[-1]['first_ts']+=STEP;f[-1]['last_ts']+=STEP;r,q,tp,runs=calculate(f)
    test('gap_keeps_observed_window_but_blocks_cross',q[20]is not None and q[20]>100 and not r[20]['cross_100_up'],
      'History follows observed order across a gap; the otherwise qualifying cross is blocked by nonadjacent anchors.')
    f=fixture(list(range(100,140)));f[10]['n']=239;r,q,tp,runs=calculate(f);ok=eligible(r,runs,25)
    bad=deepcopy(r);bad[24]['n']=239
    anchor=deepcopy(f);anchor[10]['ts']+=60;ar,aq,at,an=calculate(anchor)
    test('selection22_and_complete_previous_current',ok and not eligible(bad,runs,25)and not eligible(ar,an,25),
      'Earlier partial coverage is permitted; incomplete previous bucket or a broken anchor chain rejects selection.')
    a1=stats(list(map(F,[50]+[100]*18+[110])))[3];a2=stats(list(map(F,[100]*19+[110])))[3]
    test('fixed_current_TP_different_window',a1!=a2,'Same current TP110 with different older observations changes the reference mean and MAD.')
    full,fr,ft,fn=calculate(inputs);cuts=(19,20,21,22,26,min(6000,len(inputs)))
    ok=all(equal(calculate(inputs[:n])[0],full[:n])for n in cuts)
    changed=deepcopy(inputs);cut=min(100,len(changed))
    for b in changed[cut:]:b['source_high_int']=200*SCALE;b['source_low_int']=SCALE;b['source_close_int']=100*SCALE
    ok=ok and equal(calculate(changed)[0][:cut],full[:cut])
    test('prefix_and_future_reading_independence',ok,'Six prefixes and mutated future HLC preserve all earlier readings; no future prices enter the formula.')
    base=list(map(F,[117,80]+[100]*17));above=stats(base+[F(103)+F(1,SCALE)])[3];below=stats(base+[F(103)-F(1,SCALE)])[3]
    test('rounded100_not_threshold_decision',above>100 and below<100 and format(export(above),'.2f')==format(export(below),'.2f')=='100.00'
      and crossed(F(100),above,F(100))and not crossed(F(100),F(100),F(100)),
      'Distinct exact readings may both display100.00; flags use exact ratios.')
    return results

def run(args,a,report):
    protocol,psha=read_json(args.protocol);source,ssha=read_json(args.source_evidence);evidence,esha=read_json(args.evidence)
    report.update(protocol_sha256=psha,source_sha256=ssha,evidence_sha256=esha)
    a.require(psha==PROTOCOL_SHA,'hash_pins','frozen protocol SHA256');a.require(ssha==SOURCE_SHA,'hash_pins','pinned H4 source SHA256')
    a.same(protocol.get('source_sha256'),SOURCE_SHA,'hash_pins','declared source hash')
    for key,v in [('period',N),('window_observations',N),('source_price_scale',SCALE),('bar_seconds',STEP)]:a.same(protocol.get(key),v,'protocol_contract',key)
    a.same(protocol.get('source_fields'),list(BASE),'protocol_contract','source field order')
    a.same(evidence.get('protocol'),protocol,'embedded_provenance','embedded protocol');a.same(evidence.get('protocol_sha256'),psha,'embedded_provenance','embedded protocol hash');a.same(evidence.get('performance_calculated'),False,'embedded_provenance','no performance')
    manifest=args.source_evidence.parent/protocol['source_manifest']
    report['optional_manifest']={'path':str(manifest),'checked':manifest.exists()}
    if manifest.exists():
        m,msha=read_json(manifest);a.same(msha,protocol['source_manifest_sha256'],'source_manifest','retained manifest byte hash')
        a.same([(Path(x['path']).name,x['sha256'])for x in m['files']],[(x['file'],x['sha256'])for x in source['data_quality']['sources']],
          'source_manifest','all source file identities');report['optional_manifest']['sha256']=msha
    a.require(set(evidence)=={'protocol','protocol_sha256','data_quality','bars','examples','teaching','performance_calculated'},'payload_structure','top-level evidence schema')
    inputs=normalize(source['bars'],a);rows,ratios,typical,runs=calculate(inputs);actual=evidence['bars']
    a.require(isinstance(actual,list),'payload_structure','bar array');a.same(len(actual),len(rows),'payload_structure','all source rows retained')
    for i,(x,y)in enumerate(zip(actual,rows)):compare_row(a,x,y,f'bars[{i}]')
    categories=('source_input_fields','derived_value_fields','discrete_flag_fields');main_fields=sum(a.counts[k]for k in categories)
    q=quality(rows,ratios,source);a.same(evidence['data_quality'],q,'quality','full recomputed quality')
    toy=teaching();a.same(protocol['teaching'],toy,'teaching','protocol teaching math');a.same(evidence['teaching'],toy,'teaching','payload teaching math')
    picked,counts=select(rows,runs,protocol);examples=evidence['examples'];a.require(isinstance(examples,list),'payload_structure','example array');a.same([c.get('tag')for c in examples],list(picked),'selection','example 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+' keys')
        for key,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(key,MISSING),v,'selection',label+'.'+key)
        compare_row(a,example.get('signal_values'),rows[i],label+'.signal');compare_row(a,example.get('previous_values'),rows[i-1],label+'.previous')
        context=example.get('bars');a.require(isinstance(context,list),'payload_structure',label+' context array');a.same(len(context),31,'selection',label+' 31 rows')
        for j,(x,y)in enumerate(zip(context,rows[i-25:i+6])):compare_row(a,x,y,f'{label}.bars[{j}]')
        cases[tag]={'index':i,'available_ts':rows[i]['ts']+STEP,'available_utc':datetime.fromtimestamp(rows[i]['ts']+STEP,timezone.utc).isoformat(),
          'cci_fraction':[ratios[i].numerator,ratios[i].denominator],'cci':str(rows[i]['cci']),'context_indices':[i-25,i+5],
          'adjacent_anchors_required':22,'earlier_partial_buckets':sum(not complete(rows[j])for j in range(i-21,i-1))}
    report.update(bar_count=len(rows),defined_cci=q['defined_cci'],null_cci=len(rows)-q['defined_cci'],quality=q,selected_cases=cases,candidate_counts=counts,
      main_bar_scalar_field_comparisons=main_fields,example_copy_scalar_field_comparisons=sum(a.counts[k]for k in categories)-main_fields,
      warmup_unavailable=min(N-1,len(rows)),zero_mad_windows=q['zero_mad_windows'],global_zero_crosses=sum(b['cross_zero_up']for b in rows),global_upper_crosses=sum(b['cross_100_up']for b in rows))
    report['edge_cases']=edge_cases(a,inputs)

def main():
    p=argparse.ArgumentParser(description=__doc__)
    for name in ('protocol','source-evidence','evidence','report'):p.add_argument('--'+name,type=Path,required=True)
    args=p.parse_args()
    if args.report.resolve()in{x.resolve()for x in(args.protocol,args.source_evidence,args.evidence)}:raise SystemExit('Report must not overwrite input')
    a=Audit();report={'checker':'cci20-independent-Fraction-current-mean-v1','method':'Explicit Fraction TP, twenty-value mean, same-current-mean MAD and CCI; no production import or integer-cancellation engine copy.',
      'scope':'Pinned published H4 inputs, all guide fields/examples, source metadata, teaching and synthetic cases. No M1 ZIP replay or profitability calculations.',
      'counting_note':'Counts are performed validation operations by category, including source/schema checks and copied example fields; not counts of unique market 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())
