"""Replay the frozen EUR/USD H1 Stochastic/EMA200 study from pinned HistData M1 ZIPs.
Requires Python3.11+, numpy and pandas. No trading-platform dependency.
All signal, price-level and net-R arithmetic uses Decimal(40); vector comparisons
use exact integer source prices and floor/ceil of unrounded Decimal thresholds.
"""
import argparse
from bisect import bisect_right
from collections import deque
from datetime import datetime, timedelta, timezone
from decimal import Decimal as D, getcontext, ROUND_FLOOR, ROUND_CEILING
from hashlib import sha256
import json
from pathlib import Path
from zoneinfo import ZoneInfo
from zipfile import ZipFile
import numpy as np
import pandas as pd
getcontext().prec=40
H=3600000;M=60000;SCALE=1000000;PIP=D('0.0001');ARMS=('baseline','filtered')
EXPECTED_PROTOCOL='26c131bbd9379a02a05dd90ea3b08b169ca356441b1d5b8e98c04dbf0ef79db2'

def epoch(s):return int(datetime.fromisoformat(s.replace('Z','+00:00')).timestamp()*1000)
def iso(t):return datetime.fromtimestamp(int(t)/1000,timezone.utc).isoformat(timespec='seconds').replace('+00:00','Z')
def price(v):return D(int(v))/SCALE
def out(v):return None if v is None else format(v,'f')
def rounded(v):return format(v.quantize(D('.000000000001')),'f')

def load_source(protocol,raw_dir):
    frames=[];sources=[];invalid=0
    end=epoch(protocol['periods']['holdout'][1])
    for s in protocol['source']['archives']:
        path=Path(raw_dir)/Path(s['path']).name;digest=sha256(path.read_bytes()).hexdigest();assert digest==s['sha256'],path.name
        rows=0
        with ZipFile(path) as z:
            for member in z.namelist():
                if not member.lower().endswith('.csv'):continue
                with z.open(member) as f:df=pd.read_csv(f,sep=';',header=None,names=['time','open','high','low','close','volume'],dtype={'time':str})
                rows+=len(df);ts=pd.to_datetime(df['time'],format='%Y%m%d %H%M%S',utc=True,errors='coerce')
                t=ts.astype('int64').to_numpy()//1000000+5*H;values=df[['open','high','low','close']].to_numpy(dtype=float)
                good=ts.notna().to_numpy()&(t%M==0)&np.isfinite(values).all(axis=1)&(values>0).all(axis=1)
                good&=(values[:,1]>=values.max(axis=1))&(values[:,2]<=values.min(axis=1));invalid+=int((~good).sum())
                values=values[good];assert np.max(np.abs(values*SCALE-np.rint(values*SCALE)))<1e-6
                frame=pd.DataFrame(np.rint(values*SCALE).astype(np.int64),columns=['open','high','low','close']);frame.insert(0,'t',t[good]);frames.append(frame[frame.t<end])
        sources.append(dict(name=path.name,sha256=digest,rows=rows,source_page=s['source_page']))
    all_rows=pd.concat(frames,ignore_index=True);unique=all_rows.drop_duplicates();conflict=unique.duplicated('t',keep=False)
    clean=unique.loc[~conflict].sort_values('t',kind='stable');q={k:clean[k].to_numpy(dtype=np.int64) for k in ('t','open','high','low','close')}
    assert np.all(np.diff(q['t'])>0)
    report=dict(source_rows=len(all_rows),invalid_rows=invalid,identical_duplicates_removed=len(all_rows)-len(unique),conflicting_timestamps_excluded=int(unique.loc[conflict,'t'].nunique()),m1_rows=len(clean),first_utc=iso(q['t'][0]),last_utc=iso(q['t'][-1]),gaps_over_one_minute=int(np.sum(np.diff(q['t'])>M)))
    return q,sources,report

def hourly(q):
    buckets=q['t']//H*H;starts=np.r_[0,np.flatnonzero(np.diff(buckets))+1];ends=np.r_[starts[1:],len(buckets)];counts=ends-starts
    all_bars=[];accepted=[]
    for a,b,n in zip(starts,ends,counts,strict=True):
        t=int(buckets[a]);complete=n==60 and q['t'][a]==t and q['t'][b-1]==t+59*M
        bar=dict(open_ms=t,utc=iso(t),open=price(q['open'][a]),high=price(q['high'][a:b].max()),low=price(q['low'][a:b].min()),close=price(q['close'][b-1]),minutes=int(n),complete=bool(complete),ema=None,k=None,d=None,atr=None,candidate=False,passes=False)
        all_bars.append(bar)
        if complete:accepted.append(bar)
    return all_bars,accepted

def decorate(bars):
    raw=[];ks=[];trs=[];ema=atr=None
    for i,b in enumerate(bars):
        c=b['close'];previous=bars[i-1] if i else None
        tr=max(b['high']-b['low'],abs(b['high']-previous['close']),abs(b['low']-previous['close'])) if previous else b['high']-b['low'];trs.append(tr)
        if i==13:atr=sum(trs)/14
        elif i>13:atr=(13*atr+tr)/14
        if i==199:ema=sum(x['close'] for x in bars[:200])/200
        elif i>199:ema+=D(2)/201*(c-ema)
        rawk=None;k=None;d=None
        if i>=4:
            window=bars[i-4:i+1];hi=max(x['high'] for x in window);lo=min(x['low'] for x in window);rawk=100*(c-lo)/(hi-lo) if hi!=lo else D(50)
        raw.append(rawk)
        if i>=6:k=sum(raw[-3:])/3
        ks.append(k)
        if i>=8:d=sum(ks[-3:])/3
        b.update(ema=ema,atr=atr,k=k,d=d)
        b['candidate']=bool(i>=199 and atr is not None and atr>0 and previous['open_ms']+H==b['open_ms'] and previous['k']<=20<k and k>d)
        b['passes']=bool(ema is not None and c>ema)
    return bars

def rollovers(start,end):
    day=datetime.fromtimestamp(start/1000,timezone.utc).date()-timedelta(days=2);last=datetime.fromtimestamp(end/1000,timezone.utc).date()+timedelta(days=2);times=[];totals=[0]
    while day<=last:
        if day.weekday()<5:
            stamp=datetime(day.year,day.month,day.day,17,tzinfo=ZoneInfo('America/New_York'));times.append(int(stamp.timestamp()*1000));totals.append(totals[-1]+(3 if day.weekday()==2 else 1))
        day+=timedelta(days=1)
    return times,totals

def simulate(q,b,start,end,cost,roll,target_first=False):
    e=b['open_ms']+H;times=q['t'];a=int(np.searchsorted(times,e))
    if a>=len(times) or times[a]!=e:return None
    limit=int(np.searchsorted(times,end));assert a<limit
    c={k:D(v)*PIP for k,v in cost.items()};fill=price(q['open'][a])+c['spread_pips']+c['slippage_pips_each_side'];risk=2*b['atr'];stop=fill-risk;target=fill+3*b['atr'];due=e+72*H
    last_due=int(np.searchsorted(times,due));z=min(limit,last_due+1)
    stop_units=int((stop*SCALE).to_integral_value(rounding=ROUND_FLOOR));target_units=int((target*SCALE).to_integral_value(rounding=ROUND_CEILING))
    hits=(q['low'][a:z]<=stop_units)|(q['high'][a:z]>=target_units)|(times[a:z]>=due);where=np.flatnonzero(hits)
    ambiguous=False;at_close=False
    if len(where):
        j=a+int(where[0]);o=price(q['open'][j])
        if o<=stop:reference=o;reason='stop_gap'
        elif o>=target:reference=target;reason='target_gap'
        elif times[j]>=due:reference=o;reason='time'
        else:
            lower=price(q['low'][j])<=stop;upper=price(q['high'][j])>=target;ambiguous=bool(lower and upper)
            reference=target if upper and (target_first or not lower) else stop;reason='target' if reference==target else 'stop'
    else:j=limit-1;reference=price(q['close'][j]);reason='boundary';at_close=True
    exit_ms=int(times[j]);roll_until=exit_ms+(M-1 if at_close else 0)
    rt,rc=roll;units=rc[bisect_right(rt,roll_until)]-rc[bisect_right(rt,e)];carry=units*c['debit_pips_per_roll_unit'];exit_fill=reference-c['slippage_pips_each_side'];comm=2*c['commission_pips_each_side'];net=(exit_fill-fill-comm-carry)/risk
    return dict(signal={k:(out(b[k]) if isinstance(b[k],D) else b[k]) for k in ('open_ms','utc','close','k','d','ema','atr','passes')},entry=dict(open_ms=e,utc=iso(e),reference=out(fill),bid=out(price(q['open'][a]))),exit=dict(open_ms=exit_ms,utc=iso(exit_ms),reference=out(reference),fill=out(exit_fill),reason=reason,at_close=at_close),stop=out(stop),target=out(target),risk=out(risk),net_r=dict(base=out(net)),ambiguous=ambiguous,roll_units=units,carry=out(carry),commissions=out(comm))

def summarize(trades):
    values=[D(t['net_r']['base']) for t in trades];total=sum(values,D(0));running=peak=dd=D(0)
    for v in values:running+=v;peak=max(peak,running);dd=max(dd,peak-running)
    return dict(trades=len(trades),wins=sum(v>0 for v in values),nonpositive=sum(v<=0 for v in values),net_r=rounded(total),mean_r=rounded(total/len(values) if values else D(0)),max_drawdown_r=rounded(dd),ambiguous=sum(t['ambiguous'] for t in trades),boundary=sum(t['exit']['reason']=='boundary' for t in trades),roll_units=sum(t['roll_units'] for t in trades))

def calendar(candidates,q,start,end,cost,roll,filtered=False,target_first=False):
    trades=[];last_exit=-1;cancelled=0
    for b in candidates:
        if filtered and not b['passes']:continue
        if b['open_ms']+H<=last_exit:continue
        trade=simulate(q,b,start,end,cost,roll,target_first)
        if trade is None:cancelled+=1;continue
        trades.append(trade);last_exit=trade['exit']['open_ms']
    return dict(trades=trades,summary=summarize(trades),cancelled_missing_entry=cancelled)

def public_bar(b):return {k:(out(v) if isinstance(v,D) else v) for k,v in b.items() if k not in ('candidate','passes')}
def execute(protocol_path,raw_dir):
    blob=Path(protocol_path).read_bytes();digest=sha256(blob).hexdigest();assert digest==EXPECTED_PROTOCOL,'Protocol changed'
    p=json.loads(blob);q,sources,coverage=load_source(p,raw_dir);all_bars,bars=hourly(q);decorate(bars);coverage.update(observed_h1=len(all_bars),accepted_h1=len(bars),partial_h1=len(all_bars)-len(bars));roll=rollovers(q['t'][0],q['t'][-1]);periods={}
    for name,bounds in p['periods'].items():
        start,end=map(epoch,bounds);candidates=[b for b in bars if b['candidate'] and start<=b['open_ms']+H<end];group={}
        for arm in ARMS:
            main=calendar(candidates,q,start,end,p['costs']['base'],roll,arm=='filtered')
            stress=calendar(candidates,q,start,end,p['costs']['stress'],roll,arm=='filtered');target=calendar(candidates,q,start,end,p['costs']['base'],roll,arm=='filtered',True)
            main['summary'].update(stress_net_r=stress['summary']['net_r'],stress_trades=stress['summary']['trades'],target_first_net_r=target['summary']['net_r'],target_first_trades=target['summary']['trades']);main['stress_summary']=stress['summary'];group[arm]=main
        isolated=[t for b in candidates if (t:=simulate(q,b,start,end,p['costs']['base'],roll)) is not None];group['diagnostic']={key:dict(trades=[t for t in isolated if t['signal']['passes']==passes],summary=summarize([t for t in isolated if t['signal']['passes']==passes])) for key,passes in (('pass',True),('reject',False))}
        group['years']={str(year):{a:summarize([t for t in group[a]['trades'] if t['exit']['utc'].startswith(str(year))]) for a in ARMS} for year in range(datetime.fromtimestamp(start/1000,timezone.utc).year,datetime.fromtimestamp((end-1)/1000,timezone.utc).year+1)};group['candidate_signals']=len(candidates);periods[name]=group
    hold=periods['holdout'];rejected=hold['diagnostic']['reject']['trades'];cases=[('filtered',hold['filtered']['trades'][0]),('rejected_loss',next(t for t in rejected if D(t['net_r']['base'])<=0)),('rejected_win',next(t for t in rejected if D(t['net_r']['base'])>0))];examples=[]
    for kind,t in cases:
        lo=t['signal']['open_ms']-6*H;hi=t['exit']['open_ms']//H*H+4*H
        h1=[public_bar(b) for b in all_bars if lo<=b['open_ms']<hi];j=int(np.searchsorted(q['t'],t['exit']['open_ms']));mini=[]
        for i in range(max(0,j-4),min(len(q['t']),j+5)):
            mini.append(dict(open_ms=int(q['t'][i]),utc=iso(q['t'][i]),**{k:out(price(q[k][i])) for k in ('open','high','low','close')}))
        examples.append(dict(kind=kind,trade=t,h1=h1,m1=mini))
    return dict(protocol=p,protocol_sha256=digest,sources=sources,coverage=coverage,periods=periods,examples=examples)

if __name__=='__main__':
    ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--protocol',type=Path,default=Path(__file__).with_name('eurusd-stochastic-protocol.json'));ap.add_argument('--raw-dir',type=Path,required=True);ap.add_argument('--output',type=Path,default=Path('eurusd-stochastic-evidence.json'));args=ap.parse_args();result=execute(args.protocol,args.raw_dir);args.output.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print(json.dumps(dict(coverage=result['coverage'],results={k:{a:g[a]['summary'] for a in ARMS} for k,g in result['periods'].items()})))
