#!/usr/bin/env python3
"""Independent exact Stochastic replay, original ZIP validation, and edge cases."""
import argparse,csv,hashlib,io,json,math,zipfile
from collections import Counter,deque
from datetime import datetime,timezone
from decimal import Decimal
from fractions import Fraction as Q
from pathlib import Path

PIN='8010d212f3ad6587ba44e33ef881761d0a004b512e7d2480e2f5fc6e1bceca3b'
WIDTH=14400;UNITS=10**8
FIELDS=('ts','open','high','low','close','volume','source_close_raw','timestamp_scale','canonical')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def crossed(a,b,c,d,adjacent=True):return bool(adjacent and None not in (a,b,c,d) and a-b<=0<c-d)

def calculate(prices):
    output=[];maxima=deque();minima=deque();raw_sum=[Q(0)];raw_bad=[0];k_sum=[Q(0)];k_bad=[0];prior_k=prior_d=None
    for index,price in enumerate(prices):
        current={key:price[key]for key in FIELDS};scaled={key:int(Decimal(str(price[key]))*UNITS)for key in ('open','high','low','close')}
        assert all(Decimal(str(price[k]))*UNITS==v for k,v in scaled.items())
        assert 0<scaled['low']<=min(scaled['open'],scaled['close'])<=max(scaled['open'],scaled['close'])<=scaled['high']
        assert current['ts']%WIDTH==0 and current['timestamp_scale']in(1000,1000000)
        assert current['canonical']==(current['source_close_raw']==(current['ts']+WIDTH)*current['timestamp_scale']-1)
        for queue,value,maximum in ((maxima,scaled['high'],True),(minima,scaled['low'],False)):
            while queue and (queue[-1][1]<=value if maximum else queue[-1][1]>=value):queue.pop()
            queue.append((index,value))
            while queue[0][0]<=index-14:queue.popleft()
        low=high=raw=None
        if index>=13:
            low=minima[0][1];high=maxima[0][1]
            if high!=low:raw=Q((scaled['close']-low)*100,high-low)
        raw_sum.append(raw_sum[-1]+(raw if raw is not None else 0));raw_bad.append(raw_bad[-1]+(raw is None))
        k=(raw_sum[-1]-raw_sum[-4])/3 if index>=2 and raw_bad[-1]==raw_bad[-4]else None
        k_sum.append(k_sum[-1]+(k if k is not None else 0));k_bad.append(k_bad[-1]+(k is None))
        d=(k_sum[-1]-k_sum[-4])/3 if index>=2 and k_bad[-1]==k_bad[-4]else None
        complete=index>=18
        if complete:
            for j in range(index-18,index+1):
                if not prices[j]['canonical'] or (j>index-18 and prices[j]['ts']!=prices[j-1]['ts']+WIDTH):complete=False;break
        current.update({'source_'+key+'_int':value for key,value in scaled.items()})
        current.update(low14=None if low is None else low/UNITS,high14=None if high is None else high/UNITS,raw_k=None if raw is None else float(raw),slow_k=None if k is None else float(k),slow_d=None if d is None else float(d),bull_cross=crossed(prior_k,prior_d,k,d,bool(index and price['ts']-prices[index-1]['ts']==WIDTH)),low_zone=None if d is None else max(k,d)<20,high_zone=None if d is None else min(k,d)>80,pair_above=None if d is None else k>d,canonical_window19=complete)
        output.append(current);prior_k,prior_d=k,d
    return output

def source_quality(rows,manifest):
    holes=[]
    for i in range(1,len(rows)):
        diff=rows[i]['ts']-rows[i-1]['ts'];assert diff>0 and diff%WIDTH==0
        if diff!=WIDTH:holes.append({'left':rows[i-1]['ts'],'right':rows[i]['ts'],'missing':diff//WIDTH-1})
    return {'rows':len(rows),'sources':manifest,'source_files':len(manifest),'gaps':holes,'missing_bars':sum(x['missing']for x in holes),'noncanonical_closes':[r['ts']for r in rows if not r['canonical']],'timestamp_units':dict(Counter(str(r['timestamp_scale'])for r in rows))}

def choose(rows):
    out=[];selected=set()
    conditions=(('low_cross',lambda r:r['bull_cross'] and r['low_zone']),('high_cross',lambda r:r['bull_cross'] and r['high_zone']),('low_zone',lambda r:r['low_zone'] and r['pair_above']is False))
    for name,condition in conditions:
        candidates=[i for i,r in enumerate(rows)if i not in selected and r['ts']>=1704067200 and r['canonical_window19'] and r['slow_d']is not None and condition(r)]
        assert candidates;i=candidates[0];selected.add(i);r=rows[i];out.append({'tag':name,'index':i,'signal_ts':r['ts'],'available_ts':r['ts']+WIDTH,'signal_values':r,'previous_values':rows[i-1],'bars':rows[i-12:i+10]})
    return out

def originals(folder,manifest):
    rows=[];verified=[]
    for item in manifest:
        p=folder/item['file'];assert p.is_file();h=sha(p);assert h==item['sha256'];parts=p.with_name(p.name+'.CHECKSUM').read_text().split();assert parts[0].lower()==h and parts[1].lstrip('*')==p.name
        with zipfile.ZipFile(p)as z:
            assert z.testzip()is None;members=[v for v in z.namelist()if v.endswith('.csv')];assert len(members)==1
            with z.open(members[0])as f:
                for record in csv.reader(io.TextIOWrapper(f,encoding='utf-8')):
                    assert len(record)==12;opening=int(record[0]);scale=10**6 if opening>=10**14 else 1000;assert opening%scale==0;t=opening//scale
                    rows.append(dict(ts=t,open=float(Decimal(record[1])),high=float(Decimal(record[2])),low=float(Decimal(record[3])),close=float(Decimal(record[4])),volume=float(Decimal(record[5])),source_close_raw=int(record[6]),timestamp_scale=scale,canonical=int(record[6])==(t+WIDTH)*scale-1))
        verified.append({'file':p.name,'sha256':h})
    rows.sort(key=lambda x:x['ts']);return rows,verified

def toy(closes,low=100,high=110):
    return [dict(ts=i*WIDTH,open=float(c),high=float(high),low=float(low),close=float(c),volume=1.0,source_close_raw=(i+1)*WIDTH*1000-1,timestamp_scale=1000,canonical=True)for i,c in enumerate(closes)]

def scenarios():
    done=[]
    def check(name,ok):assert ok,name;done.append(name)
    rows=calculate(toy([105]*30));check('raw first at observation14',next(i for i,r in enumerate(rows)if r['raw_k']is not None)==13);check('slowK first at16',next(i for i,r in enumerate(rows)if r['slow_k']is not None)==15);check('slowD first at18',next(i for i,r in enumerate(rows)if r['slow_d']is not None)==17);check('19 canonical observations for examples',not rows[17]['canonical_window19'] and rows[18]['canonical_window19']);check('flat window unavailable',all(r['raw_k']is None and r['slow_d']is None for r in calculate(toy([100]*30,100,100))));check('lowest close maps to0',calculate(toy([100]*20))[-1]['raw_k']==0);check('highest close maps to100',calculate(toy([110]*20))[-1]['raw_k']==100);check('midrange maps to50',rows[-1]['raw_k']==50);sample=calculate(toy([105]*13+[101,102,109]));check('SMA of last three normalized values',sample[-1]['slow_k']==40);check('previous equality permits new cross',crossed(Q(20),Q(20),Q(21),Q(20)));check('current equality is no cross',not crossed(Q(19),Q(20),Q(20),Q(20)));check('pair order alone is no new cross',not crossed(Q(21),Q(20),Q(22),Q(20)));check('gap prevents cross',not crossed(Q(19),Q(20),Q(21),Q(20),False));check('null previous prevents cross',not crossed(None,Q(20),Q(21),Q(20)));check('exact20 outside strict low zone',calculate(toy([102]*25))[-1]['low_zone']is False);check('exact80 outside strict high zone',calculate(toy([108]*25))[-1]['high_zone']is False);check('low zone may have no cross',calculate(toy([101]*25))[-1]['low_zone']is True and not calculate(toy([101]*25))[-1]['bull_cross']);check('high zone may have no cross',calculate(toy([109]*25))[-1]['high_zone']is True and not calculate(toy([109]*25))[-1]['bull_cross'])
    changing=toy([100]*14+[105]*12,100,100)
    for r in changing[14:]:r['high']=110
    rr=calculate(changing);check('null propagation delays slowK',rr[15]['slow_k']is None and rr[16]['slow_k']is not None);check('null propagation delays slowD',rr[17]['slow_d']is None and rr[18]['slow_d']is not None)
    bad=toy([105]*25);bad[10]['source_close_raw']-=1000;bad[10]['canonical']=False;check('noncanonical close blocks example window',not calculate(bad)[24]['canonical_window19'])
    base=toy([101,109,102,108,103,107]*6);shift=[dict(r,**{k:r[k]*7+13 for k in ('open','high','low','close')})for r in base];a=calculate(base);b=calculate(shift);check('positive affine price invariance',all(all(x[k]==y[k]for k in ('raw_k','slow_k','slow_d','bull_cross','low_zone','high_zone'))for x,y in zip(a,b,strict=True)))
    return done

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--protocol',type=Path,required=True);p.add_argument('--evidence',type=Path,required=True);p.add_argument('--source-evidence',type=Path);p.add_argument('--raw-dir',type=Path);p.add_argument('--report',type=Path,required=True);a=p.parse_args();protocol=json.loads(a.protocol.read_text());e=json.loads(a.evidence.read_text());assert sha(a.protocol)==e['protocol_sha256']==PIN and e['protocol']==protocol and e['performance_calculated']is False
    base=[{k:r[k]for k in FIELDS}for r in e['bars']];archives=[]
    if a.source_evidence:
        assert sha(a.source_evidence)==protocol['source_sha256'];s=json.loads(a.source_evidence.read_text());assert base==[{k:r[k]for k in FIELDS}for r in s['bars']]
    if a.raw_dir:
        raw,archives=originals(a.raw_dir,protocol['source_manifest']);assert raw==base
    rebuilt=calculate(base);numeric=exact=0;maximum=0.0
    def compare(x,y):
        nonlocal numeric,exact,maximum
        if isinstance(x,dict):assert set(x)==set(y);[compare(x[k],y[k])for k in x]
        elif isinstance(x,list):assert len(x)==len(y);[compare(v,w)for v,w in zip(x,y,strict=True)]
        elif type(x)is float:
            assert type(y)in(int,float) and math.isfinite(x)and math.isfinite(y);error=abs(x-y);maximum=max(maximum,error);assert error<=1e-10;(None);numeric+=1
        else:assert type(x)is type(y)and x==y;(None);exact+=1
    compare(rebuilt,e['bars']);compare(choose(rebuilt),e['examples']);compare(source_quality(base,protocol['source_manifest']),e['data_quality']);cases=scenarios()
    report=dict(status='passed',checked_at_utc=datetime.now(timezone.utc).isoformat(),protocol_sha256=PIN,evidence_sha256=sha(a.evidence),checker_sha256=sha(__file__),comparison=dict(numeric_values_compared=numeric,exact_values_compared=exact,failures=0,maximum_absolute_error=maximum),synthetic_tests=cases,raw_verification=dict(source_files=len(archives),archives=archives),examples_verified=3)
    a.report.parent.mkdir(parents=True,exist_ok=True);a.report.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(json.dumps({k:report[k]for k in ('status','comparison','examples_verified')},ensure_ascii=False))

if __name__=='__main__':main()
