"""Rebuild the frozen ETH H4 CMF20/matched-OBV20 agreement study. Python stdlib only."""
from pathlib import Path
from decimal import Decimal
from datetime import datetime,timezone
from hashlib import sha256
import argparse,csv,gzip,io,json,math,zipfile
from fractions import Fraction as F

PROTOCOL_SHA='9eb9a1183d5d98df054c8732e73ca4431fc31d62bf407f5c3a85fbb9417261cf'
STEP=14400
def epoch(s):return int(datetime.fromisoformat(s.replace('Z','+00:00')).timestamp())
def iso(t):return datetime.fromtimestamp(t,timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
def integer(s,scale):
    v=Decimal(s);assert v.is_finite()and v*scale==(v*scale).to_integral_value(),s
    return int(v*scale)
def read_source(raw,manifest,protocol):
    rows=[];units={};verified=[]
    for item in manifest['files']:
        path=raw/item['file'];payload=path.read_bytes();digest=sha256(payload).hexdigest();sidecar=path.with_name(path.name+'.CHECKSUM')
        assert digest==item['sha256']==sidecar.read_text().split()[0],path.name
        assert sha256(sidecar.read_bytes()).hexdigest()==item['checksum_sha256'],sidecar.name
        previous=None;count=0
        with zipfile.ZipFile(io.BytesIO(payload))as z:
            assert z.testzip()is None,path.name
            assert [n for n in z.namelist()if n.endswith('.csv')]==[item['csv_member']],path.name
            with io.TextIOWrapper(z.open(item['csv_member']),'utf-8',newline='')as stream:
                for fields in csv.reader(stream):
                    assert len(fields)==12,(path.name,count)
                    opening=int(fields[0]);unit=1000000 if opening>=100000000000000 else 1000
                    assert opening%unit==0;ts=opening//unit;assert ts%STEP==0
                    assert datetime.fromtimestamp(ts,timezone.utc).strftime('%Y-%m')==path.stem[-7:]
                    assert previous is None or ts>previous;previous=ts
                    ints=[integer(x,protocol['price_scale'])for x in fields[1:5]];vi=integer(fields[5],protocol['volume_scale'])
                    o,h,l,c=ints;assert 0<l<=min(o,c)<=max(o,c)<=h and vi>=0
                    values=list(map(float,fields[1:6]));assert all(math.isfinite(x)for x in values)
                    close_raw=int(fields[6]);rows.append(dict(ts=ts,source_open_raw=opening,source_close_raw=close_raw,timestamp_scale=unit,open=values[0],high=values[1],low=values[2],close=values[3],volume=values[4],open_int=o,high_int=h,low_int=l,close_int=c,volume_int=vi,canonical=close_raw==(ts+STEP)*unit-1,source_fields=fields))
                    units[str(unit)]=units.get(str(unit),0)+1;count+=1
        verified.append(dict(file=path.name,sha256=digest,rows=count,crc_verified=True))
    rows.sort(key=lambda b:b['ts']);assert rows and len(rows)==len({b['ts']for b in rows})
    gaps=[dict(left=a['ts'],right=b['ts'],missing=(b['ts']-a['ts'])//STEP-1)for a,b in zip(rows,rows[1:])if b['ts']!=a['ts']+STEP]
    quality=dict(rows=len(rows),source_files=len(verified),sources=verified,gaps=gaps,missing_bars=sum(g['missing']for g in gaps),noncanonical_closes=[b['ts']for b in rows if not b['canonical']],timestamp_units=units,zero_volume_rows=sum(b['volume_int']==0 for b in rows))
    return rows,quality

def ratio_fields(row,key,value):
    row[key]=None if value is None else float(value)
    row[key+'_num']=None if value is None else str(value.numerator)
    row[key+'_den']=None if value is None else str(value.denominator)

def indicators(rows):
    segment=[];trs=[];atr=None;flows=[];flatflows=[];signed=[];flatsigned=[];obv=flatobv=0
    scale=100000000
    for i,b in enumerate(rows):
        if not b['canonical']or(i and b['ts']!=rows[i-1]['ts']+STEP):
            segment=[];trs=[];atr=None;flows=[];flatflows=[];signed=[];flatsigned=[];obv=flatobv=0
        b.update(canonical_run=0,atr14=None,eligible=False,cmf_cross=False,constant_cross=False,exit_level=False,constant_exit_level=False,direction=None,signed_volume_int=None,signed_volume=None,obv_int=None,obv=None,obv_change20_int=None,obv_change20=None,window_volume_int=None,window_volume=None,constant_obv_change20_int=None,constant_obv_change20=None)
        for key in('mfm','mfv','window_mfv','cmf','obv_balance20','constant_cmf','constant_obv_balance20'):ratio_fields(b,key,None)
        if not b['canonical']:continue
        prior=segment[-1]if segment else None
        tr=max(b['high']-b['low'],abs(b['high']-prior['close']),abs(b['low']-prior['close']))if prior else b['high']-b['low']
        trs.append(tr)
        if atr is not None:atr=(13*atr+tr)/14
        elif len(trs)==14:atr=math.fsum(trs)/14
        vi=b['volume_int'];fv=scale if vi>0 else 0
        if prior:
            direction=(b['close_int']>prior['close_int'])-(b['close_int']<prior['close_int']);delta=direction*vi;fd=direction*fv
            obv+=delta;flatobv+=fd;signed.append(delta);flatsigned.append(fd)
            b.update(direction=direction,signed_volume_int=delta,signed_volume=delta/scale)
        span=b['high_int']-b['low_int'];mfm=F(2*b['close_int']-b['high_int']-b['low_int'],span)if span else F(0)
        flows.append((mfm*vi,vi));flatflows.append((mfm*fv,fv));segment.append(b)
        b.update(canonical_run=len(segment),atr14=atr,obv_int=obv,obv=obv/scale)
        ratio_fields(b,'mfm',mfm);ratio_fields(b,'mfv',mfm*F(vi,scale))
        if len(flows)>=20:
            window=flows[-20:];v=sum(x[1]for x in window);mf=sum((x[0]for x in window),F(0));fw=flatflows[-20:];flatv=sum(x[1]for x in fw);flatmf=sum((x[0]for x in fw),F(0))
            b.update(window_volume_int=v,window_volume=v/scale)
            ratio_fields(b,'window_mfv',mf/scale);ratio_fields(b,'cmf',mf/v if v else None);ratio_fields(b,'constant_cmf',flatmf/flatv if flatv else None)
            b['exit_level']=b['cmf_num']is not None and int(b['cmf_num'])<=0
            b['constant_exit_level']=b['constant_cmf_num']is not None and int(b['constant_cmf_num'])<=0
            if len(segment)>=21:
                change=sum(signed[-20:]);fchange=sum(flatsigned[-20:]);assert change==obv-segment[-21]['obv_int']
                b.update(obv_change20_int=change,obv_change20=change/scale,constant_obv_change20_int=fchange,constant_obv_change20=fchange/scale)
                ratio_fields(b,'obv_balance20',F(change,v)if v else None);ratio_fields(b,'constant_obv_balance20',F(fchange,flatv)if flatv else None)
        if prior:
            if prior['cmf_num']is not None and b['cmf_num']is not None:b['cmf_cross']=int(prior['cmf_num'])<=0<int(b['cmf_num'])
            if prior['constant_cmf_num']is not None and b['constant_cmf_num']is not None:b['constant_cross']=int(prior['constant_cmf_num'])<=0<int(b['constant_cmf_num'])
        b['eligible']=len(segment)>=100 and atr is not None and atr>0 and b['cmf_num']is not None and prior is not None and prior['cmf_num']is not None and b['obv_change20_int']is not None
    return rows

def signal(b,model):
    if not b['eligible']:return False
    if model=='constant_volume':return b['constant_cross']and b['constant_obv_change20_int']is not None and b['constant_obv_change20_int']>0
    if not b['cmf_cross']:return False
    if model=='no_obv':return True
    assert model=='primary';return b['obv_change20_int']>0

def summarize(trades,equity,initial,exposure,capped,canceled,rejected):
    pnls=[t['pnl']for t in trades];pos=math.fsum(x for x in pnls if x>0);neg=-math.fsum(x for x in pnls if x<0)
    return dict(return_pct=100*(equity[-1]['equity']/initial-1),end_cash=equity[-1]['equity'],drawdown_pct=max(x['drawdown_pct']for x in equity),trades=len(trades),wins=sum(x>0 for x in pnls),losses=sum(x<0 for x in pnls),zero_trades=sum(x==0 for x in pnls),profit_factor=pos/neg if neg else None,mean_r=math.fsum(t['net_r']for t in trades)/len(trades)if trades else None,fees=math.fsum(t['fees']for t in trades),exposure_pct=100*exposure/len(equity),cash_capped=capped,canceled_missing_entry=canceled,rejected_entry=rejected,gap_trades=sum(t['crosses_gap']for t in trades),noncanonical_trades=sum(t['touches_noncanonical']for t in trades),delayed_cmf_exits=sum(t['delayed_cmf_exit']for t in trades),partial_close_proxies=sum(t['partial_close_proxy']for t in trades),early_terminal_proxies=sum(t['early_terminal_proxy']for t in trades),entry_slippage=math.fsum(t['qty']*(t['entry']-t['entry_ref'])for t in trades),exit_slippage=math.fsum(t['qty']*(t['exit_ref']-t['exit'])for t in trades),turnover=math.fsum(t['qty']*(t['entry']+t['exit'])for t in trades)/initial)

def simulate(rows,p,model,cost,period):
    start,end=map(epoch,p['periods'][period]);indices=[i for i,b in enumerate(rows)if start<=b['ts']<end];assert indices
    costs=p[{'base':'base_costs','zero':'zero_costs','higher':'higher_costs'}[cost]];f=costs['fee_each_side'];s=costs['slippage_each_side'];initial=float(p['initial_cash'])
    cash=initial;peak=initial;position=None;entry_pending=None;exit_pending=None;trades=[];equity=[];candidates=[];exposure=capped=canceled=rejected=0
    first=indices[0]
    if first and rows[first-1]['ts']+STEP==start and signal(rows[first-1],model):entry_pending=first-1
    def liquidate(event,b,index):
        nonlocal cash,position,exit_pending
        x=position;ref,reason,stamp,precision=event;sale=ref*(1-s);fees=f*x['qty']*(x['entry']+sale)
        if reason=='stop':net_unit=-x['unit_loss'];sign=-1
        else:
            raw_int=b['open_int']if precision=='open'else b['close_int'];sf=F(str(s));ff=F(str(f))
            exact=F(raw_int,p['price_scale'])*(1-sf)*(1-ff)-F(x['entry_ref_int'],p['price_scale'])*(1+sf)*(1+ff)
            net_unit=float(exact);sign=(exact>0)-(exact<0)
        pnl=x['qty']*net_unit;new_cash=x['cash_before']+pnl
        assert math.isclose(new_cash,cash+x['qty']*sale*(1-f),abs_tol=1e-7)
        cash=new_cash
        trades.append(dict(**x,exit_bar_ts=b['ts'],exit_event_ts=stamp,exit_precision=precision,exit_ref=ref,exit=sale,reason=reason,fees=fees,pnl=pnl,pnl_sign=sign,net_r=pnl/x['risk_cash'],delayed_cmf_exit=reason=='cmf_exit'and exit_pending is not None and b['ts']>exit_pending,partial_close_proxy=precision=='close'and not b['canonical'],early_terminal_proxy=reason=='period_end'and b['ts']+STEP<end))
        position=None;exit_pending=None
    for i in indices:
        b=rows[i];held=position is not None;exited_open=False
        if position:
            if i and position['entry_ts']<=rows[i-1]['ts']and b['ts']!=rows[i-1]['ts']+STEP:position['crosses_gap']=True
            if not b['canonical']:position['touches_noncanonical']=True
            event=None;deadline=position['entry_ts']+p['holding_limit_intervals']*STEP
            if b['open']<=position['stop']:event=(b['open'],'stop_gap',b['ts'],'open')
            elif exit_pending is not None:event=(b['open'],'cmf_exit',b['ts'],'open')
            elif b['ts']>=deadline:event=(b['open'],'time_delayed',b['ts'],'open')
            if event:liquidate(event,b,i);exited_open=True
        if entry_pending is not None:
            sig=rows[entry_pending];scheduled=sig['ts']+STEP
            if b['ts']!=scheduled:canceled+=1
            elif position is None and not exited_open:
                entry=b['open']*(1+s);stop=entry-2*sig['atr14'];unit=entry*(1+f)-stop*(1-s)*(1-f)
                if not(0<stop<b['open']and unit>0 and cash>0):rejected+=1
                else:
                    riskq=p['risk_fraction']*cash/unit;cashq=cash/(entry*(1+f));qty=min(riskq,cashq);cap=cashq<riskq;before=cash;cash-=qty*entry*(1+f)
                    assert cash>=-1e-8;cash=max(0.,cash)
                    position=dict(signal_bar_ts=sig['ts'],signal_ts=scheduled,entry_ts=b['ts'],entry_ref=b['open'],entry_ref_int=b['open_int'],entry=entry,stop=stop,qty=qty,risk_cash=qty*unit,unit_loss=unit,cash_before=before,cash_capped=cap,signal_cmf=sig['constant_cmf']if model=='constant_volume'else sig['cmf'],signal_obv_change20=sig['constant_obv_change20']if model=='constant_volume'else sig['obv_change20'],signal_atr14=sig['atr14'],crosses_gap=False,touches_noncanonical=not b['canonical'])
                    held=True;capped+=int(cap)
            else:raise AssertionError('Pending entry conflicts with carried position/open exit')
            entry_pending=None
        if position:
            x=position;deadline=x['entry_ts']+p['holding_limit_intervals']*STEP;event=None
            if b['low']<=x['stop']:event=(x['stop'],'stop',b['ts'],'within_4h')
            elif b['ts']+STEP>=deadline:event=(b['close'],'time',b['ts']+STEP,'close')
            elif i==indices[-1]:event=(b['close'],'period_end',b['ts']+STEP,'close')
            if event:liquidate(event,b,i)
            elif (b['constant_exit_level']if model=='constant_volume'else b['exit_level'])and exit_pending is None:exit_pending=b['ts']+STEP
        exposure+=int(held);marked=cash+(position['qty']*b['close']*(1-s)*(1-f)if position else 0);peak=max(peak,marked)
        equity.append(dict(ts=b['ts']+STEP,bar_ts=b['ts'],equity=marked,drawdown_pct=100*(peak-marked)/peak))
        if b['eligible']and(b['constant_cross']if model=='constant_volume'else b['cmf_cross']):
            action='held'if position is not None else'outside_period'if b['ts']+STEP>=end else'queued'if signal(b,model)else'filter_rejected'
            candidates.append(dict(ts=b['ts'],available=b['ts']+STEP,real_cmf=b['cmf'],real_obv_change20=b['obv_change20'],real_gate=b['obv_change20_int']>0,flat_after_events=position is None,action=action))
        if position is None and b['ts']+STEP<end and signal(b,model):entry_pending=i
    if entry_pending is not None and rows[entry_pending]['ts']+STEP<end:canceled+=1
    assert position is None and math.isclose(cash,initial+math.fsum(t['pnl']for t in trades),abs_tol=1e-7)
    annual=[];last=initial
    for year in sorted({datetime.fromtimestamp(e['ts']-1,timezone.utc).year for e in equity}):
        point=next(e for e in reversed(equity)if datetime.fromtimestamp(e['ts']-1,timezone.utc).year==year);annual.append(dict(year=year,return_pct=100*(point['equity']/last-1)));last=point['equity']
    return dict(model=model,cost=cost,period=period,start_ts=start,end_ts=end,fee=f,slippage=s,metrics=summarize(trades,equity,initial,exposure,capped,canceled,rejected),trades=trades,equity=equity,annual=annual,candidates=candidates)

def passive(rows,p,period):
    start,end=map(epoch,p['periods'][period]);bars=[b for b in rows if start<=b['ts']<end];f=p['base_costs']['fee_each_side'];s=p['base_costs']['slippage_each_side'];initial=p['initial_cash'];entry=bars[0]['open']*(1+s);qty=initial/(entry*(1+f));peak=initial;equity=[]
    for b in bars:
        value=qty*b['close']*(1-s)*(1-f);peak=max(peak,value);equity.append(dict(ts=b['ts']+STEP,bar_ts=b['ts'],equity=value,drawdown_pct=100*(peak-value)/peak))
    return dict(period=period,metrics=dict(return_pct=100*(equity[-1]['equity']/initial-1),end_cash=equity[-1]['equity'],drawdown_pct=max(e['drawdown_pct']for e in equity),exposure_pct=100),equity=equity)

def compute(protocol_path,manifest_path,raw):
    assert sha256(protocol_path.read_bytes()).hexdigest()==PROTOCOL_SHA,'Frozen protocol mismatch'
    p=json.loads(protocol_path.read_text());m=json.loads(manifest_path.read_text());assert sha256(manifest_path.read_bytes()).hexdigest()==p['source_manifest_sha256']
    rows,quality=read_source(raw,m,p);indicators(rows)
    quality['zero_range_rows']=sum(b['high_int']==b['low_int']for b in rows)
    quality['defined_cmf_rows']=sum(b['cmf']is not None for b in rows)
    quality['source_fingerprint_sha256']=sha256(''.join(','.join(b['source_fields'])+'\n'for b in rows).encode()).hexdigest()
    runs={f'{model}_{cost}_{period}':simulate(rows,p,model,cost,period)for model in('primary','no_obv')for cost in('base','zero','higher')for period in('full','early','later')}
    runs.update({f'constant_volume_base_{period}':simulate(rows,p,'constant_volume','base',period)for period in('full','early','later')})
    early=next(iter(runs['primary_base_early']['trades']),None);later_trades=runs['primary_base_later']['trades'];later=next(iter(later_trades),None)
    opposite=next((t for t in later_trades if later is not None and t['pnl_sign']*later['pnl_sign']<0),None)
    selected=opposite if opposite is not None else later_trades[1]if len(later_trades)>1 else None
    selection_kind='opposite_sign'if opposite is not None else'next_later'if selected is not None else'unavailable'
    examples=[]
    for tag,t in(('early',early),('later',later),('opposite',selected)):
        if t is None:examples.append(dict(tag=tag,available=False,selection_kind='unavailable'));continue
        signal_i=next(i for i,b in enumerate(rows)if b['ts']==t['signal_bar_ts']);exit_i=next(i for i,b in enumerate(rows)if b['ts']==t['exit_bar_ts'])
        examples.append(dict(tag=tag,available=True,selection_kind=selection_kind if tag=='opposite'else'first_chronological',trade=t,bars=rows[max(0,signal_i-20):exit_i+4]))
    return dict(protocol=p,protocol_sha256=sha256(protocol_path.read_bytes()).hexdigest(),manifest=m,manifest_sha256=sha256(manifest_path.read_bytes()).hexdigest(),data_quality=quality,bars=rows,runs=runs,buy_hold={period:passive(rows,p,period)for period in p['periods']},examples=examples)

def main():
    a=argparse.ArgumentParser();a.add_argument('--protocol',type=Path,required=True);a.add_argument('--manifest',type=Path,required=True);a.add_argument('--raw-dir',type=Path,required=True);a.add_argument('--output',type=Path,required=True);x=a.parse_args()
    x.output.parent.mkdir(parents=True,exist_ok=True);lock=dict(calculated_at_utc=datetime.now(timezone.utc).isoformat(),code_sha256=sha256(Path(__file__).read_bytes()).hexdigest(),protocol_sha256=sha256(x.protocol.read_bytes()).hexdigest(),manifest_sha256=sha256(x.manifest.read_bytes()).hexdigest())
    lock_path=x.output.parent/'primary-code-lock.json'
    if lock_path.exists():
        previous=json.loads(lock_path.read_text());assert all(previous[k]==lock[k]for k in('code_sha256','protocol_sha256','manifest_sha256')),'Code/protocol revision needs an explicit recorded correction.'
    else:lock_path.write_text(json.dumps(lock,indent=2)+'\n')
    data=compute(x.protocol,x.manifest,x.raw_dir);payload=(json.dumps(data,separators=(',',':'),allow_nan=False)+'\n').encode()
    x.output.write_bytes(gzip.compress(payload,compresslevel=6,mtime=0)if x.output.suffix=='.gz'else payload)
    result_lock=dict(code_sha256=lock['code_sha256'],protocol_sha256=lock['protocol_sha256'],manifest_sha256=lock['manifest_sha256'],result_sha256=sha256(payload).hexdigest(),bytes=len(payload),stored_bytes=x.output.stat().st_size)
    (x.output.parent/'primary-result-lock.json').write_text(json.dumps(result_lock,indent=2)+'\n')
    print(json.dumps(dict(status='calculated',rows=len(data['bars']),quality={k:data['data_quality'][k]for k in('source_files','missing_bars','noncanonical_closes','zero_volume_rows','zero_range_rows')},runs={k:{m:v['metrics'][m]for m in('return_pct','drawdown_pct','trades','profit_factor')}for k,v in data['runs'].items()},examples=[dict(tag=c['tag'],available=c['available'],pnl=c.get('trade',{}).get('pnl'))for c in data['examples']]),indent=2))
if __name__=='__main__':main()
