#!/usr/bin/env python3
"""Independent stdlib/Decimal50 ETHUSDT CMF20/matched-OBV20 rebuild.

Only the frozen protocol, source manifest and79 original H4 archives are inputs.
No primary implementation, derived indicator array or account ledger is read.
"""
from __future__ import annotations
import argparse,bisect,calendar,csv,datetime as dt,gzip,hashlib,io,json,re,zipfile
from collections import deque,Counter
from decimal import Decimal,getcontext
from fractions import Fraction
from pathlib import Path

getcontext().prec=50
D=Decimal
F=Fraction
ZERO=D(0)
ONE=D(1)
HUNDRED=D(100)
SCALE=100000000
STEP=14400
UTC=dt.timezone.utc
PROTOCOL_SHA='9eb9a1183d5d98df054c8732e73ca4431fc31d62bf407f5c3a85fbb9417261cf'
MANIFEST_SHA='bb0292a1befecb050bdb37b9850698a27ee46d2069f9c953eacee4a4411651c5'

def sha(path):
    h=hashlib.sha256()
    with Path(path).open('rb')as stream:
        while chunk:=stream.read(1024*1024):h.update(chunk)
    return h.hexdigest()
def epoch(s):return int(dt.datetime.fromisoformat(s.replace('Z','+00:00')).timestamp())
def iso(t):return dt.datetime.fromtimestamp(t,UTC).isoformat().replace('+00:00','Z')
def px(v):return D(v)/SCALE
def dec_fraction(v):return D(v.numerator)/D(v.denominator)
def sgn(v):return (v>0)-(v<0)
def ratio_fields(prefix,value):
    return {prefix:None if value is None else dec_fraction(value),prefix+'_num':None if value is None else str(value.numerator),prefix+'_den':None if value is None else str(value.denominator),prefix+'_sign':None if value is None else sgn(value)}

def scaled(s,positive):
    try:value=D(s)
    except Exception as exc:raise ValueError('invalid scaled source value')from exc
    if not value.is_finite()or(value<=0 if positive else value<0):raise ValueError('invalid finite source sign')
    exact=F(s)*SCALE
    if exact.denominator!=1:raise ValueError('source precision finer than1e-8')
    return exact.numerator

def parse_row(fields,filename,row_number):
    if len(fields)!=12:raise ValueError('expected exactly12 source columns')
    if not re.fullmatch(r'\d+',fields[0])or not re.fullmatch(r'\d+',fields[6]):raise ValueError('noninteger source timestamp')
    raw_open=int(fields[0]);raw_close=int(fields[6]);unit=1000000 if raw_open>=100000000000000 else 1000
    if raw_open%unit:raise ValueError('source opening timestamp is not integral seconds')
    t=raw_open//unit
    if t%STEP:raise ValueError('source opening is not on UTC H4 grid')
    month=re.fullmatch(r'ETHUSDT-4h-(\d{4})-(\d{2})\.zip',filename)
    if month is None:raise ValueError('unrecognized selected archive name')
    opening=dt.datetime.fromtimestamp(t,UTC)
    if(opening.year,opening.month)!=(int(month[1]),int(month[2])):raise ValueError('opening outside named archive month')
    o,h,l,c=[scaled(s,True)for s in fields[1:5]];v=scaled(fields[5],False)
    if not l<=min(o,c)<=max(o,c)<=h:raise ValueError('invalid OHLC bounds')
    return dict(ts=t,source_open_raw=raw_open,source_close_raw=raw_close,source_unit=unit,raw_fields=fields,source_file=filename,source_row=row_number,
                open_int=o,high_int=h,low_int=l,close_int=c,volume_int=v,open=px(o),high=px(h),low=px(l),close=px(c),volume=px(v),
                scheduled_close_ts=t+STEP,canonical=raw_close==(t+STEP)*unit-1)

def read_source(folder,manifest,start,end):
    files=manifest['files']
    if len(files)!=79 or len({f['file']for f in files})!=79:raise ValueError('expected79 distinct selected archives')
    bars=[];archives=[];seen=set();raw_rows=0
    for selected in files:
        path=folder/selected['file'];sidecar=folder/(selected['file']+'.CHECKSUM')
        digest=sha(path)
        if digest!=selected['sha256']or path.stat().st_size!=selected['bytes']:raise ValueError('source archive pin mismatch')
        if sha(sidecar)!=selected['checksum_sha256']:raise ValueError('source CHECKSUM sidecar pin mismatch')
        lines=sidecar.read_text(encoding='ascii').strip().splitlines()
        if len(lines)!=1:raise ValueError('unexpected checksum sidecar record count')
        tokens=lines[0].split()
        if len(tokens)!=2 or tokens[0].lower()!=digest or tokens[1].lstrip('*')!=selected['file']:raise ValueError('CHECKSUM does not bind exact archive')
        with zipfile.ZipFile(path)as archive:
            if archive.namelist()!=[selected['csv_member']]:raise ValueError('unexpected archive member identities')
            bad=archive.testzip()
            if bad is not None:raise ValueError('source ZIP CRC failed')
            info=archive.getinfo(selected['csv_member']);previous=None;count=0;retained=0
            with archive.open(info)as raw:
                with io.TextIOWrapper(raw,encoding='ascii',newline='')as stream:
                    for count,fields in enumerate(csv.reader(stream),1):
                        bar=parse_row(fields,selected['file'],count);t=bar['ts']
                        if previous is not None and t<=previous:raise ValueError('archive anchors not strictly increasing')
                        previous=t
                        if t in seen:raise ValueError('duplicate source opening anchor')
                        seen.add(t)
                        if start<=t<end:bars.append(bar);retained+=1
            raw_rows+=count;archives.append(dict(file=selected['file'],sha256=digest,checksum_sha256=sha(sidecar),bytes=path.stat().st_size,csv_member=info.filename,member_bytes=info.file_size,member_crc32=f'{info.CRC:08x}',crc_verified=True,rows=count,retained_rows=retained))
    bars.sort(key=lambda b:b['ts']);normal=hashlib.sha256();raw_hash=hashlib.sha256();gaps=[]
    for j,b in enumerate(bars):
        normal.update((';'.join(str(b[k])for k in('ts','open_int','high_int','low_int','close_int','volume_int'))+'\n').encode('ascii'))
        raw_hash.update((','.join(b['raw_fields'])+'\n').encode('ascii'))
        missing=0 if j==0 else(b['ts']-bars[j-1]['ts'])//STEP-1;b['missing_before']=missing
        if missing:gaps.append(dict(left=bars[j-1]['ts'],right=b['ts'],missing_intervals=missing))
    quality=dict(archives=archives,raw_rows=raw_rows,retained_rows=len(bars),normalized_sha256=normal.hexdigest(),normalized_encoding='Sorted retained rows: ts;Oint;Hint;Lint;Cint;Vint plus LF, ASCII.',raw12_sha256=raw_hash.hexdigest(),raw12_encoding='Sorted retained rows: comma-joined original12 fields plus LF, ASCII.',gaps=gaps,missing_intervals=sum(g['missing_intervals']for g in gaps),noncanonical_rows=sum(not b['canonical']for b in bars),zero_volume_rows=sum(b['volume_int']==0 for b in bars),zero_range_rows=sum(b['high_int']==b['low_int']for b in bars),timestamp_units=dict(Counter(str(b['source_unit'])for b in bars)))
    return bars,quality

def indicators(bars):
    prev=None;segment=0;run=0;atr=None;trs=[];window=deque();obvs=deque();mfv_sum=F(0);flat_sum=F(0);volume_sum=flat_volume_sum=0;obv=flat_obv=0
    for index,b in enumerate(bars):
        reset=not b['canonical']or prev is None or not prev['canonical']or b['ts']!=prev['ts']+STEP
        if reset:
            run=0;atr=None;trs=[];window.clear();obvs.clear();mfv_sum=flat_sum=F(0);volume_sum=flat_volume_sum=obv=flat_obv=0
        b.update(index=index,segment=None,run=0,tr=None,atr14=None,obv_int=None,flat_obv_int=None,signed_volume_int=None,flat_signed_volume_int=None,change20_int=None,flat_change20_int=None,window_volume_int=None,flat_window_volume_int=None,eligible=False,cross=False,flat_cross=False,obv_gate=False,flat_obv_gate=False,exit_cmf=False,flat_exit_cmf=False)
        for name in('mfm','mfv','cmf','flat_cmf','balance','flat_balance'):b.update(ratio_fields(name,None))
        if not b['canonical']:prev=b;continue
        if run==0:segment+=1
        run+=1;h,l,c,v=b['high_int'],b['low_int'],b['close_int'],b['volume_int'];fv=SCALE if v>0 else 0
        tr=px(h-l)if run==1 else max(px(h-l),abs(px(h-prev['close_int'])),abs(px(l-prev['close_int'])))
        if run<=14:
            trs.append(tr)
            if run==14:atr=sum(trs,ZERO)/14
        else:atr=(13*atr+tr)/14
        direction=0 if run==1 else sgn(c-prev['close_int']);signed=direction*v;flat_signed=direction*fv;obv+=signed;flat_obv+=flat_signed
        mfm=F(2*c-h-l,h-l)if h>l else F(0);mfv=mfm*v;flat_mfv=mfm*fv
        window.append((mfv,flat_mfv,v,fv));mfv_sum+=mfv;flat_sum+=flat_mfv;volume_sum+=v;flat_volume_sum+=fv
        if len(window)>20:
            a,d,x,y=window.popleft();mfv_sum-=a;flat_sum-=d;volume_sum-=x;flat_volume_sum-=y
        obvs.append((obv,flat_obv))
        if len(obvs)>21:obvs.popleft()
        cmf=mfv_sum/volume_sum if len(window)==20 and volume_sum>0 else None
        flat_cmf=flat_sum/flat_volume_sum if len(window)==20 and flat_volume_sum>0 else None
        change=obv-obvs[0][0]if len(obvs)==21 else None;flat_change=flat_obv-obvs[0][1]if len(obvs)==21 else None
        balance=F(change,volume_sum)if change is not None and volume_sum else None
        flat_balance=F(flat_change,flat_volume_sum)if flat_change is not None and flat_volume_sum else None
        b.update(segment=segment,run=run,tr=tr,atr14=atr,obv_int=obv,flat_obv_int=flat_obv,signed_volume_int=signed,flat_signed_volume_int=flat_signed,change20_int=change,flat_change20_int=flat_change,window_volume_int=volume_sum if len(window)==20 else None,flat_window_volume_int=flat_volume_sum if len(window)==20 else None,obv_gate=change is not None and change>0,flat_obv_gate=flat_change is not None and flat_change>0)
        for name,value in(('mfm',mfm),('mfv',mfv/SCALE),('cmf',cmf),('flat_cmf',flat_cmf),('balance',balance),('flat_balance',flat_balance)):b.update(ratio_fields(name,value))
        same_previous=run>1 and prev is not None and prev['canonical']and prev['segment']==segment
        b['eligible']=bool(run>=100 and atr is not None and atr>0 and cmf is not None and same_previous and prev['cmf_sign']is not None and change is not None)
        b['cross']=bool(same_previous and prev['cmf_sign']is not None and cmf is not None and prev['cmf_sign']<=0<b['cmf_sign'])
        b['flat_cross']=bool(same_previous and prev['flat_cmf_sign']is not None and flat_cmf is not None and prev['flat_cmf_sign']<=0<b['flat_cmf_sign'])
        b['exit_cmf']=cmf is not None and cmf<=0;b['flat_exit_cmf']=flat_cmf is not None and flat_cmf<=0
        prev=b
    return bars

def cost_values(protocol,key):
    source=protocol[{'base':'base_costs','zero':'zero_costs','higher':'higher_costs'}[key]]
    f=F(str(source['fee_each_side']));s=F(str(source['slippage_each_side']))
    return dict(fee=dec_fraction(f),slip=dec_fraction(s),fee_fraction=f,slip_fraction=s)

def quote_net(entry_int,reference_int,cost):
    f,s=cost['fee_fraction'],cost['slip_fraction']
    return F(reference_int,SCALE)*(1-s)*(1-f)-F(entry_int,SCALE)*(1+s)*(1+f)

def size_position(cash,opening,atr,cost,risk_fraction):
    e=opening*(1+cost['slip']);stop=e-2*atr
    unit=e*(1+cost['fee'])-stop*(1-cost['slip'])*(1-cost['fee'])
    if not ZERO<stop<opening or unit<=0 or cash<=0:return None
    riskq=risk_fraction*cash/unit;cashq=cash/(e*(1+cost['fee']));q=min(riskq,cashq)
    if q<=0:return None
    reserve=ZERO if q==cashq else cash-q*e*(1+cost['fee'])
    if reserve < -D('1e-35'):raise ArithmeticError('cash-funded sizing borrowed cash')
    return dict(entry=e,stop=stop,lunit=unit,qty=q,risk_cash=q*unit,cash_capped=cashq<riskq,cash_reserved=reserve)

def diagnostic_trade(bars,entry_index,exit_index):
    selected=bars[entry_index:exit_index+1]
    return dict(crosses_gap=any(b['missing_before']>0 for b in selected[1:]),missing_intervals=sum(b['missing_before']for b in selected[1:]),touches_noncanonical=any(not b['canonical']for b in selected),noncanonical_rows=sum(not b['canonical']for b in selected))

def close_position(position,b,index,reason,precision,reference,cost,bars,period_end):
    q=position['qty'];x=reference*(1-cost['slip']);entry_fee=position['entry_fee'];exit_fee=q*x*cost['fee']
    exact=None
    if reason=='stop':pnl=-q*position['lunit'];sign=-1
    else:
        ref_int=b['open_int']if precision=='open'else b['close_int'];exact=quote_net(position['entry_int'],ref_int,cost);pnl=q*dec_fraction(exact);sign=sgn(exact)
    cash=position['cash_before']+pnl;from_reserved=position['cash_reserved']+q*x*(1-cost['fee'])
    if abs(cash-from_reserved)>D('1e-34')*max(ONE,abs(cash)):raise ArithmeticError('reserved-cash liquidation failed to reconcile')
    event_ts=b['ts']if precision in('open','within_4h')else b['ts']+STEP
    t={k:v for k,v in position.items()if k not in('cash_reserved','entry_int','entry_index','queued_exit')}
    t.update(exit_bar_ts=b['ts'],exit_event_ts=event_ts,exit_precision=precision,reason=reason,exit_ref=reference,exit=x,exit_fee=exit_fee,fees=entry_fee+exit_fee,pnl=pnl,pnl_sign=sign,net_r=pnl/position['risk_cash'],cash_after=cash,net_unit_num=None if exact is None else str(exact.numerator),net_unit_den=None if exact is None else str(exact.denominator),entry_slippage=q*(position['entry']-position['entry_ref']),exit_slippage=q*(reference-x),turnover_notional=q*(position['entry']+x),exit_signal_ts=position['queued_exit'],delayed_cmf_exit=reason=='cmf_exit'and event_ts>position['queued_exit'],partial_close_proxy=precision=='close'and not b['canonical'],early_terminal_proxy=reason=='period_end'and b['ts']+STEP<period_end)
    t.update(diagnostic_trade(bars,position['entry_index'],index));return t,cash

def summarize(trades,equity,initial,occupied,canceled,rejected):
    end=trades[-1]['cash_after']if trades else initial;wins=sum(t['pnl_sign']>0 for t in trades);losses=sum(t['pnl_sign']<0 for t in trades)
    gains=sum((t['pnl']for t in trades if t['pnl_sign']>0),ZERO);loss=-sum((t['pnl']for t in trades if t['pnl_sign']<0),ZERO)
    total=lambda key:sum((t[key]for t in trades),ZERO)
    return dict(return_pct=100*(end/initial-1),end_cash=end,trades=len(trades),wins=wins,losses=losses,zero_trades=len(trades)-wins-losses,profit_factor=gains/loss if loss else None,mean_r=total('net_r')/len(trades)if trades else None,drawdown_pct=max((x['drawdown_pct']for x in equity),default=ZERO),fees=total('fees'),exposure_pct=100*D(occupied)/len(equity)if equity else ZERO,cash_capped=sum(t['cash_capped']for t in trades),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=total('entry_slippage'),exit_slippage=total('exit_slippage'),turnover=total('turnover_notional')/initial,turnover_notional=total('turnover_notional'))

def annual_rows(equity,initial):
    years={}
    for row in equity:years[dt.datetime.fromtimestamp(row['bar_ts'],UTC).year]=row['equity']
    result=[];previous=initial
    for year,last in years.items():
        result.append(dict(year=year,start_equity=previous,end_equity=last,return_pct=100*(last/previous-1)));previous=last
    return result

def study(bars,protocol,model,cost_key,period):
    begin,end=map(epoch,protocol['periods'][period]);initial=D(str(protocol['initial_cash']));risk=D(str(protocol['risk_fraction']));cash=initial;cost=cost_values(protocol,cost_key)
    evaluation=[i for i,b in enumerate(bars)if begin<=b['ts']<end];indices={b['ts']:i for i,b in enumerate(bars)};trades=[];equity=[];candidates=[];position=None;pending=None;occupied_count=canceled=rejected=0;peak=initial
    series='flat_'if model=='constant_volume'else''
    def queue(signal_index):
        nonlocal pending
        b=bars[signal_index];available=b['ts']+STEP
        if not begin<=available<end or not b['eligible']or not b[series+'cross']:return
        gate=b[series+'obv_gate'];action='held'if position is not None else'obv_rejected'if model!='no_obv'and not gate else'queued_entry'
        rec=dict(signal_bar_ts=b['ts'],signal_ts=available,cmf=b[series+'cmf'],cmf_num=b[series+'cmf_num'],cmf_den=b[series+'cmf_den'],change20_int=b[series+'change20_int'],obv_gate=gate,common_eligible=True,flat_at_signal=position is None,at_signal_action=action,action=action)
        candidates.append(rec)
        if action=='queued_entry':pending=dict(signal_index=signal_index,candidate=rec,ts=available)
    previous=indices.get(begin-STEP)
    if previous is not None:queue(previous)
    for order,index in enumerate(evaluation):
        b=bars[index];t=b['ts'];held_at_open=position is not None;entered=False;opening_exit=False
        if pending is not None and pending['ts']<t:
            pending['candidate']['action']='missing_entry';canceled+=1;pending=None
        if position is not None:
            reason='stop_gap'if b['open']<=position['stop']else'cmf_exit'if position['queued_exit']is not None else'time_delayed'if t>=position['deadline']else None
            if reason is not None:
                trade,cash=close_position(position,b,index,reason,'open',b['open'],cost,bars,end);trades.append(trade);position=None;opening_exit=True
        if pending is not None and pending['ts']==t:
            if position is not None or opening_exit:pending['candidate']['action']='opening_blocked'
            else:
                signal=bars[pending['signal_index']];sized=size_position(cash,b['open'],signal['atr14'],cost,risk)
                if sized is None:pending['candidate']['action']='invalid_entry';rejected+=1
                else:
                    q=sized['qty'];entry_fee=q*sized['entry']*cost['fee'];position=dict(sized,number=len(trades)+1,model=model,cost=cost_key,period=period,signal_bar_ts=signal['ts'],signal_ts=t,entry_ts=t,entry_ref=b['open'],entry_int=b['open_int'],entry_index=index,cash_before=cash,entry_fee=entry_fee,signal_atr14=signal['atr14'],signal_cmf=signal[series+'cmf'],signal_cmf_num=signal[series+'cmf_num'],signal_cmf_den=signal[series+'cmf_den'],signal_cmf_real=signal['cmf'],signal_cmf_flat=signal['flat_cmf'],signal_change20_int=signal[series+'change20_int'],signal_real_change20_int=signal['change20_int'],signal_flat_change20_int=signal['flat_change20_int'],deadline=t+int(protocol['holding_limit_intervals'])*STEP,queued_exit=None)
                    cash=sized['cash_reserved'];entered=True;pending['candidate']['action']='entered'
            pending=None
        if held_at_open or entered:occupied_count+=1
        if position is not None:
            reason='stop'if b['low']<=position['stop']else'time'if t+STEP>=position['deadline']else'period_end'if order==len(evaluation)-1 else None
            if reason is not None:
                precision='within_4h'if reason=='stop'else'close';reference=position['stop']if reason=='stop'else b['close'];trade,cash=close_position(position,b,index,reason,precision,reference,cost,bars,end);trades.append(trade);position=None
        value=cash if position is None else cash+position['qty']*b['close']*(1-cost['slip'])*(1-cost['fee']);peak=max(peak,value)
        equity.append(dict(ts=t+STEP,bar_ts=t,equity=value,drawdown_pct=100*(peak-value)/peak,occupied=held_at_open or entered))
        if position is not None and b[series+'exit_cmf']and position['queued_exit']is None:position['queued_exit']=t+STEP
        queue(index)
    if pending is not None:
        pending['candidate']['action']='missing_entry';canceled+=1
    if position is not None:raise AssertionError('terminal position remained')
    metrics=summarize(trades,equity,initial,occupied_count,canceled,rejected)
    if equity and equity[-1]['equity']!=cash:raise ArithmeticError('final cash/mark mismatch')
    return dict(model=model,cost=cost_key,period=period,start_ts=begin,end_ts=end,metrics=metrics,trades=trades,equity=equity,annual=annual_rows(equity,initial),candidates=candidates)

def buy_hold(bars,protocol,period):
    begin,end=map(epoch,protocol['periods'][period]);evaluation=[i for i,b in enumerate(bars)if begin<=b['ts']<end];initial=D(str(protocol['initial_cash']));cost=cost_values(protocol,'base');equity=[];peak=initial
    if not evaluation:return dict(metrics=dict(return_pct=ZERO,end_cash=initial,drawdown_pct=ZERO,fees=ZERO),trades=[],equity=[],annual=[])
    first,last=bars[evaluation[0]],bars[evaluation[-1]];entry=first['open']*(1+cost['slip']);q=initial/(entry*(1+cost['fee']));reserve=initial-q*entry*(1+cost['fee']);exit=last['close']*(1-cost['slip']);net=quote_net(first['open_int'],last['close_int'],cost);pnl=q*dec_fraction(net);final=initial+pnl;fees=q*(entry+exit)*cost['fee']
    for index in evaluation:
        b=bars[index];value=final if index==evaluation[-1]else reserve+q*b['close']*(1-cost['slip'])*(1-cost['fee']);peak=max(peak,value);equity.append(dict(ts=b['ts']+STEP,bar_ts=b['ts'],equity=value,drawdown_pct=100*(peak-value)/peak))
    trade=dict(entry_ts=first['ts'],entry_ref=first['open'],entry=entry,qty=q,exit_bar_ts=last['ts'],exit_event_ts=last['ts']+STEP,exit_ref=last['close'],exit=exit,fees=fees,pnl=pnl,pnl_sign=sgn(net),cash_after=final,net_unit_num=str(net.numerator),net_unit_den=str(net.denominator),partial_close_proxy=not last['canonical'],early_terminal_proxy=last['ts']+STEP<end)
    trade.update(diagnostic_trade(bars,evaluation[0],evaluation[-1]));return dict(period=period,start_ts=begin,end_ts=end,metrics=dict(return_pct=100*(final/initial-1),end_cash=final,drawdown_pct=max(x['drawdown_pct']for x in equity),fees=fees,exposure_pct=HUNDRED),trades=[trade],equity=equity,annual=annual_rows(equity,initial))

def select_examples(runs,bars):
    early=runs['primary_base_early']['trades'];later=runs['primary_base_later']['trades'];third=None;kind='unavailable'
    if later:
        first_sign=later[0]['pnl_sign']
        if first_sign:third=next((t for t in later[1:]if t['pnl_sign']==-first_sign),None)
        if third is not None:kind='first_later_opposite_sign'
        elif len(later)>1:third=later[1];kind='next_later_trade'
    chosen=[('early',early[0]if early else None,'first_early'),('later',later[0]if later else None,'first_later'),('opposite',third,kind)];index={b['ts']:i for i,b in enumerate(bars)};result=[]
    for tag,trade,selection in chosen:
        if trade is None:result.append(dict(tag=tag,available=False,selection_kind='unavailable'));continue
        a=index[trade['signal_bar_ts']];z=index[trade['exit_bar_ts']];result.append(dict(tag=tag,available=True,selection_kind=selection,outcome_conditioned=selection=='first_later_opposite_sign',trade=trade,bars=bars[max(0,a-20):min(len(bars),z+4)]))
    return result

def synthetic_tests(protocol):
    tests=[]
    def check(name,value):
        if not value:raise AssertionError(name)
        tests.append(dict(id=name,status='passed'))
    def rejects(fn):
        try:fn()
        except(ValueError,ArithmeticError):return True
        return False
    start=epoch('2020-01-01T00:00:00Z')
    def candle(i,o=100,h=110,l=90,c=100,v=1,canonical=True):
        t=start+i*STEP;values=[str(t*1000),str(o),str(h),str(l),str(c),str(v),str((t+STEP)*1000-1),'0','0','0','0','0'];b=parse_row(values,'ETHUSDT-4h-2020-01.zip',i+1);b['canonical']=canonical;b['missing_before']=0;return b
    check('price_integer_scale',scaled('1.00000001',True)==100000001)
    check('nonfinite_price_rejected',rejects(lambda:scaled('NaN',True)))
    check('negative_volume_rejected',rejects(lambda:scaled('-1',False)))
    check('genuine_zero_volume_valid',scaled('0',False)==0)
    check('nonrepresentable_source_rejected',rejects(lambda:scaled('1.000000001',True)))
    b=candle(0);check('milliseconds_canonical',b['canonical']and b['source_unit']==1000)
    raw=b['raw_fields'][:];raw[0]=str(start*1000000);raw[6]=str((start+STEP)*1000000-1);check('microseconds_canonical',parse_row(raw,'ETHUSDT-4h-2020-01.zip',1)['canonical'])
    raw=b['raw_fields'][:];raw[6]=str((start+STEP)*1000);check('close_label_anomaly_retained',not parse_row(raw,'ETHUSDT-4h-2020-01.zip',1)['canonical'])
    raw=b['raw_fields'][:];raw[0]=str(start*1000+1);check('fractional_open_second_rejected',rejects(lambda:parse_row(raw,'ETHUSDT-4h-2020-01.zip',1)))
    raw=b['raw_fields'][:];raw[0]=str((start+60)*1000);check('misaligned_open_rejected',rejects(lambda:parse_row(raw,'ETHUSDT-4h-2020-01.zip',1)))
    check('opening_month_only_check',candle(185)['canonical'])
    bad=b['raw_fields'][:];bad[1]='111';check('invalid_OHLC_rejected',rejects(lambda:parse_row(bad,'ETHUSDT-4h-2020-01.zip',1)))
    rows=indicators([candle(i,c=101 if i else 100)for i in range(21)])
    check('CMF20_available_at20_prices',rows[19]['cmf_sign']==1)
    check('OBV20_requires21_prices',rows[19]['change20_int']is None and rows[20]['change20_int']is not None)
    check('OBV_first_segment_value_zero',rows[0]['obv_int']==0)
    check('equal_close_signed_volume_zero',rows[2]['signed_volume_int']==0)
    check('matched20_change_excludes_first_price',rows[20]['change20_int']==SCALE and rows[20]['window_volume_int']==20*SCALE)
    zero=indicators([candle(i,v=0)for i in range(21)]);check('zero_window_unavailable_without_reset',zero[-1]['run']==21 and zero[-1]['cmf']is None and zero[-1]['change20_int']==0 and zero[-1]['balance']is None)
    zr=indicators([candle(i,h=100,l=100,c=100,v=2)for i in range(20)]);check('zero_range_volume_stays_denominator',zr[-1]['cmf_sign']==0 and zr[-1]['window_volume_int']==40*SCALE)
    mixed=indicators([candle(i,c=110)for i in range(19)]+[candle(19,h=100,l=100,c=100,v=19)]);check('zero_range_dilutes_CMF',mixed[-1]['cmf_num']=='1'and mixed[-1]['cmf_den']=='2')
    flattened=indicators([candle(i,c=110,v=0 if i==10 else 9)for i in range(21)]);check('flat_positive_one_true_zero_zero',flattened[-1]['flat_window_volume_int']==19*SCALE)
    exact=indicators([candle(i,c=110 if i<10 else 90)for i in range(20)]);check('CMF_exact_zero_sign',exact[-1]['cmf_sign']==0)
    positive=indicators([candle(i,c='100.00000001')for i in range(20)]);check('tiny_positive_not_display_zero',positive[-1]['cmf_sign']==1 and positive[-1]['cmf']<D('.0001'))
    stable=indicators([candle(i,c=99 if i<99 else 110)for i in range(100)]);check('mask99_100',not stable[98]['eligible']and stable[99]['eligible'])
    gap=[candle(i)for i in range(102)];gap[100]['ts']+=STEP;gap[101]['ts']+=STEP;indicators(gap);check('gap_resets_history',gap[100]['run']==1 and gap[101]['run']==2 and gap[100]['obv_int']==0)
    anomaly=[candle(i,canonical=i!=99)for i in range(102)];indicators(anomaly);check('noncanonical_resets_both_sides',anomaly[99]['run']==0 and anomaly[99]['cmf']is None and anomaly[100]['run']==1)
    zeros=indicators([candle(i,v=0 if i==90 else 1)for i in range(100)]);check('zero_volume_does_not_reset_mask',zeros[-1]['run']==100 and zeros[-1]['eligible'])
    flat100=indicators([candle(i,h=100,l=100,c=100)for i in range(100)]);check('zero_ATR_blocks_entry',not flat100[-1]['eligible'])
    unavailable=indicators([candle(i,v=0 if i<20 else 1,c=110)for i in range(21)]);check('unavailable_to_positive_not_cross',unavailable[19]['cmf']is None and not unavailable[20]['cross'])
    cross=indicators([candle(i,c=100 if i<20 else 110)for i in range(21)]);check('exact_zero_to_positive_cross',cross[-1]['cross'])
    negative=indicators([candle(i,c=99 if i<20 else 100)for i in range(21)]);check('current_zero_not_positive_cross',not negative[-1]['cross'])
    cost=cost_values(protocol,'base');sized=size_position(D(10000),D(100),D(1),cost,D('.01'))
    check('cash_funded_sizing_cap',sized['qty']*sized['entry']*(1+cost['fee'])<=D(10000)+D('1e-40')and sized['risk_cash']<=100)
    check('invalid_known_open_protection',size_position(D(10000),D(100),D('.0001'),cost,D('.01'))is None)
    check('nonpositive_stop_rejected',size_position(D(10000),D(100),D(100),cost,D('.01'))is None)
    z=cost_values(protocol,'zero');check('quoted_exact_zero_no_epsilon',quote_net(100*SCALE,100*SCALE,z)==0)
    check('quoted_one_source_unit_sign',quote_net(100*SCALE,100*SCALE+1,z)>0 and quote_net(100*SCALE,100*SCALE-1,z)<0)
    check('base_fees_and_slip_both_legs',quote_net(100*SCALE,100*SCALE,cost)<0)
    # Account event tests use explicit valid precomputed indicator fixtures.
    def account_fixture(count=4):
        items=indicators([candle(j,h=101,l=99)for j in range(count)])
        for j,b in enumerate(items):b.update(atr14=D(1),eligible=True,cross=j==0,flat_cross=j==0,obv_gate=True,flat_obv_gate=True,exit_cmf=False,flat_exit_cmf=False)
        return items
    def account(items,hold=30,model='primary',cost_key='base',end_index=None):
        p=dict(protocol);p['periods']={'full':[iso(start+STEP),iso(start+(len(items)if end_index is None else end_index)*STEP)]};p['holding_limit_intervals']=hold;return study(items,p,model,cost_key,'full')
    items=account_fixture();r=account(items);check('entry_next_open_only',r['trades'][0]['entry_ts']==start+STEP)
    items=account_fixture();items[1]['canonical']=False;r=account(items);check('entry_future_noncanonical_not_censored',len(r['trades'])==1 and r['trades'][0]['touches_noncanonical'])
    items=account_fixture();del items[1];r=account(items);check('missing_entry_canceled_not_deferred',not r['trades']and r['metrics']['canceled_missing_entry']==1)
    items=account_fixture();items[0]['obv_gate']=False;a=account(items);b=account(items,model='no_obv');check('control_removes_only_OBV_gate',not a['trades']and len(b['trades'])==1)
    items=account_fixture();items[0]['cross']=False;items[0]['flat_cross']=True;a=account(items);b=account(items,model='constant_volume');check('flat_rebuild_cross_controls_calendar',not a['trades']and len(b['trades'])==1)
    items=account_fixture();items[1]['low']=D(95);r=account(items);check('entry_interval_stop_first',r['trades'][0]['reason']=='stop'and r['trades'][0]['exit_bar_ts']==items[1]['ts'])
    items=account_fixture();items[1]['exit_cmf']=True;items[2]['open']=D(95);items[2]['open_int']=95*SCALE;r=account(items);check('stop_gap_before_queued_CMF',r['trades'][0]['reason']=='stop_gap')
    items=account_fixture();items[1]['exit_cmf']=True;r=account(items,hold=1);check('surviving_time_close_before_next_open_exit',r['trades'][0]['reason']=='time'and r['trades'][0]['exit_precision']=='close')
    items=account_fixture(6);items[1]['exit_cmf']=True;del items[2];items[2]['missing_before']=1;items[2]['exit_cmf']=False;r=account(items,hold=2);check('pending_CMF_persists_and_beats_missed_time',r['trades'][0]['reason']=='cmf_exit'and r['trades'][0]['delayed_cmf_exit']and r['trades'][0]['crosses_gap'])
    items=account_fixture(6);del items[2];items[2]['missing_before']=1;r=account(items,hold=2);check('missed_time_uses_next_actual_open',r['trades'][0]['reason']=='time_delayed'and r['trades'][0]['exit_precision']=='open')
    items=account_fixture();r=account(items,hold=2);check('entry_interval_one_time_close',r['trades'][0]['reason']=='time'and r['trades'][0]['exit_event_ts']==start+3*STEP)
    items=account_fixture();items[2]['cross']=True;items[2]['low']=D(95);r=account(items);check('intrabar_exit_close_signal_can_queue_next_open',len(r['trades'])==2)
    items=account_fixture();items[1]['exit_cmf']=True;items[2]['cross']=True;r=account(items);check('opening_exit_no_same_open_reentry',r['trades'][0]['exit_bar_ts']==items[2]['ts']and(r['trades'][1]['entry_ts']if len(r['trades'])>1 else start+100*STEP)>items[2]['ts'])
    items=account_fixture();items[-1]['canonical']=False;r=account(items);check('terminal_noncanonical_close_proxy',r['trades'][0]['reason']=='period_end'and r['trades'][0]['partial_close_proxy'])
    items=account_fixture();r=account(items,end_index=6);check('early_terminal_last_observed_close',r['trades'][0]['early_terminal_proxy']and r['trades'][0]['exit_event_ts']==start+4*STEP)
    items=account_fixture();r=account(items,cost_key='zero');check('zero_net_account_sign',r['metrics']['zero_trades']==1 and r['metrics']['wins']==0 and r['metrics']['losses']==0)
    items=account_fixture();items[0]['cross']=False;r=account(items);check('zero_trade_metrics',r['metrics']['return_pct']==0 and r['metrics']['drawdown_pct']==0 and r['metrics']['profit_factor']is None and r['metrics']['mean_r']is None)
    yr=annual_rows([dict(ts=epoch('2021-01-01T00:00:00Z'),bar_ts=epoch('2020-12-31T20:00:00Z'),equity=D(10100))],D(10000));check('annual_opening_year',yr[0]['year']==2020)
    def example_trade(sign,number):return dict(pnl_sign=sign,number=number,signal_bar_ts=start,exit_bar_ts=start+STEP)
    def gallery(later):return select_examples({'primary_base_early':{'trades':[]},'primary_base_later':{'trades':later}},[candle(0),candle(1)])[2]
    check('gallery_first_opposite_sign',gallery([example_trade(-1,1),example_trade(-1,2),example_trade(1,3)])['trade']['number']==3)
    check('gallery_no_opposite_next_chronological',gallery([example_trade(-1,1),example_trade(0,2)])['selection_kind']=='next_later_trade')
    check('gallery_zero_first_has_no_opposite',gallery([example_trade(0,1),example_trade(1,2),example_trade(-1,3)])['trade']['number']==2)
    check('gallery_unavailable_when_no_next',not gallery([example_trade(-1,1)])['available'])
    check('gallery_no_first_unavailable',not gallery([])['available'])
    return dict(status='passed',assertions=len(tests),cases=tests)

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--raw',required=True);parser.add_argument('--protocol',required=True);parser.add_argument('--manifest');parser.add_argument('--output',required=True);args=parser.parse_args()
    pp=Path(args.protocol);mp=Path(args.manifest)if args.manifest else pp.with_name(pp.name.replace('protocol.json','source-manifest.json'))
    if not mp.is_file():mp=pp.with_name('source-manifest.json')
    if sha(pp)!=PROTOCOL_SHA or sha(mp)!=MANIFEST_SHA:raise ValueError('frozen protocol/manifest pin mismatch')
    protocol=json.loads(pp.read_text());manifest=json.loads(mp.read_text());out=Path(args.output);out.parent.mkdir(parents=True,exist_ok=True)
    lock=dict(stage='before_first_synthetic_or_source_price_calculation',at_utc=dt.datetime.now(UTC).isoformat(),code_sha256=sha(__file__),protocol_sha256=sha(pp),manifest_sha256=sha(mp),decimal_precision=50,independence='Own original-ZIP loader, exact Fraction CMF and integer OBV windows, Decimal account engine. No primary code, derived data or ledger is an executable input.')
    lp=out.parent/('independent-calculation-lock-'+lock['code_sha256'][:12]+'.json')
    if lp.exists():
        previous=json.loads(lp.read_text())
        if previous['code_sha256']!=lock['code_sha256']:raise ValueError('lock collision')
    else:lp.write_text(json.dumps(lock,indent=2)+'\n')
    tests=synthetic_tests(protocol);print(json.dumps(dict(stage='synthetics',assertions=tests['assertions'])),flush=True)
    start=epoch(protocol['warmup_start']);end=max(epoch(pair[1])for pair in protocol['periods'].values());bars,quality=read_source(Path(args.raw),manifest,start,end);print(json.dumps(dict(stage='source_verified',rows=len(bars),normalized_sha256=quality['normalized_sha256'],raw12_sha256=quality['raw12_sha256'])),flush=True);indicators(bars)
    runs={}
    for model in('primary','no_obv','constant_volume'):
        for cost in(('base',)if model=='constant_volume'else('base','zero','higher')):
            for period in protocol['periods']:
                key=f'{model}_{cost}_{period}';runs[key]=study(bars,protocol,model,cost,period);print(json.dumps(dict(stage='account_complete',key=key,trades=len(runs[key]['trades']))),flush=True)
    result=dict(status='independently_rebuilt_pending_primary_comparison',lock=lock,protocol_sha256=lock['protocol_sha256'],manifest_sha256=lock['manifest_sha256'],quality=quality,bars=bars,runs=runs,buy_hold={period:buy_hold(bars,protocol,period)for period in protocol['periods']},examples=select_examples(runs,bars),synthetic_tests=tests)
    with out.open('wb')as raw:
        with gzip.GzipFile(fileobj=raw,mode='wb',mtime=0)as compressed:
            with io.TextIOWrapper(compressed,encoding='utf-8')as stream:json.dump(result,stream,default=str,ensure_ascii=False,allow_nan=False,separators=(',',':'))
    summary=dict(status=result['status'],code_sha256=lock['code_sha256'],result_sha256=sha(out),result_hash_scope='gzip archive bytes',protocol_sha256=lock['protocol_sha256'],manifest_sha256=lock['manifest_sha256'],synthetic_assertions=tests['assertions'],source_rows=len(bars),runs=len(runs),trades=sum(len(run['trades'])for run in runs.values()),equity_rows=sum(len(run['equity'])for run in runs.values()))
    (out.parent/'independent-result-lock.json').write_text(json.dumps(summary,indent=2)+'\n');print(json.dumps(summary),flush=True)

if __name__=='__main__':main()
