#!/usr/bin/env python3
"""Independent Decimal50 verifier for the frozen Ethereum Fisher Transform10 and EMA200 study.

Standard library only. This file neither imports nor executes the main replay.
Indicators are rebuilt by contiguous canonical segments. Execution uses a full
scheduled UTC H4 clock, with separate opening, range and completed-close phases.
Source reconstruction is mandatory for a historical verification. Supply the
protocol, evidence JSON, and directory holding all 79 ZIP/CHECKSUM pairs.

  python eth-fisher-independent-check.py --protocol eth-fisher-protocol.json \
    --evidence eth-fisher-evidence.json --raw-dir raw --report check.json
  python eth-fisher-independent-check.py --synthetic-only --report synthetic.json

Account amounts tolerate 1e-6 USDT; prices, indicators and dimensionless numeric
metrics 1e-8; quantities 1e-12 ETH. Counts, signs, events and timestamps are exact.
An intrabar stop marks a four-hour interval, not an observed exact tick time.
"""
import argparse
from collections import Counter
import copy
import csv
import datetime as dt
from decimal import Decimal, getcontext
import hashlib
import io
import json
from pathlib import Path
import sys
import zipfile

getcontext().prec = 50
D = Decimal
ZERO, ONE, HUNDRED = D(0), D(1), D(100)
STEP = 14400
FROZEN_SHA256 = "4789aeab9a715fb6d5eb559950401adc89534ee95352b1375316a212dc1a4205"
TOLERANCES = {"account_USDT":D("1e-6"),"price_indicator_or_metric":D("1e-8"),"quantity_ETH":D("1e-12")}
ACCOUNT_KEYS = {"cash_before","risk_cash","fees","pnl","equity","end_cash","entry_slippage","exit_slippage","retained_pnl"}
RAW_FIELDS = ("ts","open","high","low","close","volume","source_close_raw","timestamp_scale","canonical")
RUNS = tuple((v,p) for v in ("primary","no_ema","zero_cost","higher_cost") for p in (("full","early","later") if v in ("primary","no_ema") else ("full",)))

class AuditError(Exception):
    pass


def require(condition, message):
    if not condition:
        raise AuditError(message)


def decimal(value):
    if isinstance(value, D):
        result = value
    else:
        result = D(str(value))
    require(result.is_finite(), "Nonfinite numeric input")
    return result


def read_json(path):
    def reject_constant(value):
        raise AuditError("Nonfinite JSON constant: " + value)
    return json.loads(path.read_text(), parse_float=D, parse_constant=reject_constant)


def epoch(value):
    return int(dt.datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())


def utc(value):
    return dt.datetime.fromtimestamp(value, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


class Comparison:
    def __init__(self):
        self.numeric_count = 0
        self.exact_count = 0
        self.failures = 0
        self.samples = []
        self.max_error = {key: ZERO for key in TOLERANCES}
        self.max_error_at = {key: None for key in TOLERANCES}

    def fail(self, path, expected, actual, detail=""):
        self.failures += 1
        if len(self.samples) < 30:
            self.samples.append({"path": path, "expected": str(expected),
                                 "actual": str(actual), "detail": detail})

    def compare(self, expected, actual, path, key=""):
        if expected is None or actual is None:
            self.exact_count += 1
            if expected is not actual:
                self.fail(path, expected, actual, "Null/validity mismatch")
            return
        if isinstance(expected, bool) or isinstance(actual, bool):
            self.exact_count += 1
            if type(expected) is not type(actual) or expected != actual:
                self.fail(path, expected, actual, "Boolean mismatch")
            return
        if isinstance(expected, dict) and isinstance(actual, dict):
            if set(expected) != set(actual):
                self.fail(path, sorted(expected), sorted(actual), "Object keys differ")
            for item in expected.keys() & actual.keys():
                self.compare(expected[item], actual[item], path + "." + item, item)
            return
        if isinstance(expected, list) and isinstance(actual, list):
            if len(expected) != len(actual):
                self.fail(path, len(expected), len(actual), "Array length differs")
            for index, (left, right) in enumerate(zip(expected, actual)):
                self.compare(left, right, "%s[%d]" % (path, index), key)
            return
        if isinstance(expected, (D, int)) and isinstance(actual, (D, int)):
            if isinstance(expected, int) and isinstance(actual, int):
                self.exact_count += 1
                if expected != actual:
                    self.fail(path, expected, actual, "Integer mismatch")
                return
            category = ("account_USDT" if key in ACCOUNT_KEYS else
                        "quantity_ETH" if key == "qty" else
                        "price_indicator_or_metric")
            error = abs(decimal(expected) - decimal(actual))
            self.numeric_count += 1
            if error > self.max_error[category]:
                self.max_error[category] = error
                self.max_error_at[category] = path
            if error > TOLERANCES[category]:
                self.fail(path, expected, actual, "Absolute difference " + str(error))
            return
        self.exact_count += 1
        if type(expected) is not type(actual) or expected != actual:
            self.fail(path, expected, actual, "Exact value/type mismatch")


def normalize_bar(values):
    bar = {key: values[key] for key in RAW_FIELDS if key != "canonical"}
    for key in ("ts", "source_close_raw", "timestamp_scale"):
        require(type(bar[key]) is int, "Invalid integer field: " + key)
    require(bar["timestamp_scale"] in (1000, 1000000), "Unsupported timestamp scale")
    require(bar["ts"] % STEP == 0, "Opening timestamp is not on the UTC H4 grid")
    for key in ("open", "high", "low", "close", "volume"):
        bar[key] = decimal(bar[key])
    require(ZERO < bar["low"] <= min(bar["open"], bar["close"])
            <= max(bar["open"], bar["close"]) <= bar["high"], "Malformed OHLC row")
    require(bar["volume"] >= ZERO, "Negative source volume")
    canonical_end = (bar["ts"] + STEP) * bar["timestamp_scale"] - 1
    bar["canonical"] = bar["source_close_raw"] == canonical_end
    return bar


def load_original_rows(folder, manifest, protocol):
    lower = epoch(protocol["warmup_start"])
    upper = max(epoch(window[1]) for window in protocol["periods"].values())
    rows = []
    verified = []
    for source in manifest:
        name = source["file"]
        path = folder / name
        if not path.is_file():
            candidates = list(folder.rglob(name))
            require(len(candidates) == 1, "Cannot uniquely locate archive " + name)
            path = candidates[0]
        archive_hash = digest(path)
        require(archive_hash == source["sha256"], "Archive differs from manifest: " + name)
        checksum = path.with_name(path.name + ".CHECKSUM")
        require(checksum.is_file(), "Missing published CHECKSUM for " + name)
        pieces = checksum.read_text().split()
        require(len(pieces) == 2 and pieces[0].lower() == archive_hash,
                "Published CHECKSUM mismatch for " + name)
        if len(pieces) > 1:
            require(pieces[1].lstrip("*") == name,
                    "CHECKSUM identifies another archive: " + name)
        count = 0
        with zipfile.ZipFile(path) as archive:
            require(archive.testzip() is None, "ZIP CRC failure: " + name)
            members = [item for item in archive.namelist() if item.endswith(".csv")]
            require(len(members) == 1, "Expected exactly one source CSV in " + name)
            with archive.open(members[0]) as binary:
                for record in csv.reader(io.TextIOWrapper(binary, encoding="utf-8")):
                    require(len(record) == 12, "Unexpected Binance row width in " + name)
                    source_open = int(record[0])
                    scale = 1000000 if source_open >= 100000000000000 else 1000
                    require(source_open % scale == 0, "Source timestamp not divisible by declared scale")
                    require(lower <= source_open // scale < upper, "Source timestamp outside frozen source interval")
                    rows.append(normalize_bar({
                        "ts": source_open // scale, "open": D(record[1]),
                        "high": D(record[2]), "low": D(record[3]),
                        "close": D(record[4]), "volume": D(record[5]),
                        "source_close_raw": int(record[6]), "timestamp_scale": scale,
                    }))
                    count += 1
        verified.append({"file": name, "sha256": archive_hash, "rows": count})
    rows.sort(key=lambda bar: bar["ts"])
    return rows, verified


def quality(rows, manifest):
    require(rows, "No price rows")
    gaps = []
    for previous, current in zip(rows, rows[1:]):
        distance = current["ts"] - previous["ts"]
        require(distance > 0 and distance % STEP == 0, "Duplicate or unordered H4 row")
        if distance > STEP:
            gaps.append({"left": previous["ts"], "right": current["ts"],
                         "missing": distance // STEP - 1})
    return {
        "rows": len(rows), "sources": manifest, "source_files": len(manifest),
        "gaps": gaps, "missing_bars": sum(item["missing"] for item in gaps),
        "noncanonical_closes": [bar["ts"] for bar in rows if not bar["canonical"]],
        "timestamp_units": dict(Counter(str(bar["timestamp_scale"]) for bar in rows)),
    }


def seeded_wilder(values, length):
    """Return arithmetic-mean seed followed by the independent delta recurrence."""
    out = [None] * len(values)
    if len(values) < length:
        return out
    out[length-1] = sum(values[:length], ZERO) / D(length)
    for j in range(length, len(values)):
        out[j] = out[j-1] + (values[j]-out[j-1]) / D(length)
    return out


def pair_cross(previous_fast,previous_slow,current_fast,current_slow):
    return all(v is not None for v in (previous_fast,previous_slow,current_fast,current_slow)) and previous_fast<=previous_slow and current_fast>current_slow


def seeded_ema(values,length):
    result=[None]*len(values)
    start=next((i for i,v in enumerate(values) if v is not None),len(values))
    if len(values)-start<length:return result
    first=start+length-1
    result[first]=sum(values[start:first+1],ZERO)/D(length)
    for i in range(first+1,len(values)):
        result[i]=(D(length-1)*result[i-1]+D(2)*values[i])/D(length+1)
    return result


INDICATOR_KEYS = ('median','median_high10','median_low10','normalized','u_raw','u','fisher','trigger','ema200','atr14')
FLAG_KEYS = ('eligible','fisher_cross','fisher_exit')


def clip_normalized(value):
    if value>D('.99'):return D('.999')
    if value<D('-.99'):return D('-.999')
    return value


def fill_segment(segment):
    """Batch canonical history; nonlinear Fisher chain is separate from EMA/ATR."""
    close=[row['close']for row in segment]
    medians=[(row['high']+row['low'])/D(2)for row in segment]
    tr=[max([row['high']-row['low']]+([abs(row['high']-close[j-1]),abs(row['low']-close[j-1])]if j else []))for j,row in enumerate(segment)]
    ema=seeded_ema(close,200);atr=seeded_wilder(tr,14)
    previous_u=previous_f=ZERO
    chain_exists=False
    for j,bar in enumerate(segment):
        bar.update(median=medians[j],ema200=ema[j],atr14=atr[j])
        if j>=9:
            window=medians[j-9:j+1]
            high,low=max(window),min(window)
            bar.update(median_high10=high,median_low10=low)
            if high==low:
                previous_u=previous_f=ZERO
                chain_exists=False
            else:
                norm=(D(2)*medians[j]-high-low)/(high-low)
                raw=D('.33')*norm+D('.67')*previous_u
                bounded=clip_normalized(raw)
                value=((ONE+bounded)/(ONE-bounded)).ln()/D(2)+previous_f/D(2)
                trigger=previous_f if chain_exists else None
                bar.update(normalized=norm,u_raw=raw,u=bounded,fisher=value,trigger=trigger)
                previous_u,previous_f=bounded,value
                chain_exists=True
        current_ready=bar['fisher']is not None and bar['trigger']is not None
        previous_ready=j>0 and segment[j-1]['fisher']is not None and segment[j-1]['trigger']is not None
        bar['fisher_cross']=bool(current_ready and previous_ready and pair_cross(segment[j-1]['fisher'],segment[j-1]['trigger'],bar['fisher'],bar['trigger']))
        bar['fisher_exit']=bool(current_ready and bar['fisher']<=bar['trigger'])
        bar['eligible']=bool(j>=199 and atr[j]is not None and atr[j]>ZERO and ema[j]is not None and current_ready and previous_ready)


def rebuild_indicators(rows):
    output=[dict(b,**dict.fromkeys(INDICATOR_KEYS),**dict.fromkeys(FLAG_KEYS,False))for b in rows]
    segment=[];previous=None
    for bar in output:
        if not bar['canonical'] or(previous is not None and bar['ts']!=previous+STEP):
            fill_segment(segment);segment=[]
        if bar['canonical']:segment.append(bar)
        previous=bar['ts']
    fill_segment(segment)
    return output


def qualifies(bar,variant):
    return bool(bar is not None and bar['eligible'] and bar['fisher_cross'] and(variant=='no_ema'or bar['close']>bar['ema200']))


def costs_for(protocol, variant):
    if variant=='zero_cost':
        return ZERO,ZERO
    costs=protocol['higher_costs'] if variant=='higher_cost' else protocol['base_costs']
    return decimal(costs['fee_each_side']),decimal(costs['slippage_each_side'])


def account_path(rows, protocol, variant, period):
    """Opening/range/close transitions driven by every scheduled clock anchor."""
    start,finish=map(epoch,protocol['periods'][period])
    by_time={b['ts']:b for b in rows}
    require(len(by_time)==len(rows),'Duplicate simulated time')
    observed=[b for b in rows if start<=b['ts']<finish]
    require(observed and observed[-1]['ts']+STEP==finish,'Missing final scheduled in-period bar')
    initial=decimal(protocol['initial_cash'])
    fee,slip=costs_for(protocol,variant)
    risk=decimal(protocol['risk_fraction'])
    cash=peak=initial
    position=None
    pending_entry=by_time.get(start-STEP)
    if not qualifies(pending_entry,variant):
        pending_entry=None
    pending_exit=None
    trades,marks=[],[]
    occupied_count=capped=canceled=rejected=0

    def close_position(bar,reference,reason,phase):
        nonlocal cash,position,pending_exit
        qty=position['qty']
        fill=reference*(ONE-slip)
        entry=position['entry']
        # Unit identity is evaluated before multiplication; do not subtract two
        # rounded position notionals to classify a mathematically zero trade.
        unit_pnl=fill*(ONE-fee)-entry*(ONE+fee)
        pnl=qty*unit_pnl
        cash+=qty*(fill*(ONE-fee))
        public={k:v for k,v in position.items() if not k.startswith('_')}
        public.update(exit_bar_ts=bar['ts'],exit_event_ts=bar['ts']+(STEP if phase=='close' else 0),
                      exit_precision=phase,exit_ref=reference,exit=fill,reason=reason,
                      fees=qty*fee*(entry+fill),pnl=pnl,net_r=pnl/position['risk_cash'],
                      holding_intervals=1+(bar['ts']-position['entry_ts'])//STEP,
                      delayed_fisher_exit=reason=='fisher_exit' and pending_exit is not None and bar['ts']>pending_exit,
                      partial_close_proxy=phase=='close' and not bar['canonical'])
        trades.append(public)
        position=None
        pending_exit=None
        require(abs(cash-initial-sum((t['pnl'] for t in trades),ZERO))<D('1e-34'),
                'Cash identity fails after a sale')

    for opening in range(start,finish,STEP):
        bar=by_time.get(opening)
        if bar is None:
            if pending_entry is not None:
                require(pending_entry['ts']+STEP==opening,'Entry queue survived a missing opening')
                pending_entry=None
                canceled+=1
            if position is not None:
                position['crosses_gap']=True
            continue
        # OPEN: purchase uses only signal state and this observed opening.
        if pending_entry is not None:
            require(position is None and pending_entry['ts']+STEP==opening,'Overlapping or delayed entry')
            fill=bar['open']*(ONE+slip)
            stop=fill-D(2)*pending_entry['atr14']
            cost_per_unit=fill*(ONE+fee)
            loss_per_unit=cost_per_unit-stop*(ONE-slip)*(ONE-fee)
            if not (ZERO<stop<bar['open'] and loss_per_unit>ZERO and cash>ZERO):
                rejected+=1
            else:
                risk_qty=risk*cash/loss_per_unit
                funding_qty=cash/cost_per_unit
                qty=min(risk_qty,funding_qty)
                require(qty.is_finite() and qty>ZERO,'Nonpositive entry quantity')
                before=cash
                cash-=qty*cost_per_unit
                require(cash>=-D('1e-40'),'Purchase borrowed cash')
                if cash<ZERO:
                    cash=ZERO
                require(qty*loss_per_unit<=risk*before+D('1e-40'),'Nominal risk budget exceeded')
                was_capped=funding_qty<risk_qty
                position=dict(signal_bar_ts=pending_entry['ts'],signal_ts=opening,
                    entry_ts=opening,entry_ref=bar['open'],entry=fill,stop=stop,qty=qty,
                    risk_cash=qty*loss_per_unit,cash_before=before,cash_capped=was_capped,
                    signal_fisher=pending_entry['fisher'],signal_trigger=pending_entry['trigger'],
                    signal_ema200=pending_entry['ema200'],signal_atr14=pending_entry['atr14'],
                    crosses_gap=False,touches_noncanonical=False,
                    _deadline=opening+int(protocol['holding_limit_intervals'])*STEP)
                capped+=int(was_capped)
            pending_entry=None
        if position is not None:
            if not bar['canonical']:
                position['touches_noncanonical']=True
            if bar['open']<=position['stop']:
                close_position(bar,bar['open'],'stop_gap','open')
            elif pending_exit is not None:
                close_position(bar,bar['open'],'fisher_exit','open')
            elif opening>=position['_deadline']:
                close_position(bar,bar['open'],'time_delayed','open')
        # Occupancy starts after all opening liquidations, unlike an account
        # that labels a position held at the opening for zero time as exposure.
        occupied=position is not None
        # RANGE: one fixed stop, no target and no invented ordering of other
        # intrabar prices. CLOSE: time, period boundary, then indicator queue.
        if position is not None:
            if bar['low']<=position['stop']:
                close_position(bar,position['stop'],'stop','within_4h')
            elif opening+STEP>=position['_deadline']:
                close_position(bar,bar['close'],'time','close')
            elif opening+STEP==finish:
                close_position(bar,bar['close'],'period_end','close')
            elif bar['fisher_exit']:
                pending_exit=opening+STEP
        occupied_count+=int(occupied)
        liquidation=position['qty']*bar['close']*(ONE-slip)*(ONE-fee) if position else ZERO
        marked=cash+liquidation
        peak=max(peak,marked)
        marks.append(dict(ts=opening+STEP,bar_ts=opening,equity=marked,
                          drawdown_pct=HUNDRED*(peak-marked)/peak))
        if position is None and opening+STEP<finish and qualifies(bar,variant):
            pending_entry=bar
    require(position is None,'Unliquidated terminal position')
    require(abs(cash-initial-sum((t['pnl'] for t in trades),ZERO))<D('1e-34'),'Terminal ledger identity fails')
    positive=sum((t['pnl'] for t in trades if t['pnl']>ZERO),ZERO)
    negative=-sum((t['pnl'] for t in trades if t['pnl']<ZERO),ZERO)
    metrics=dict(return_pct=HUNDRED*(cash/initial-ONE),end_cash=cash,
        drawdown_pct=max(m['drawdown_pct'] for m in marks),trades=len(trades),
        wins=sum(t['pnl']>ZERO for t in trades),losses=sum(t['pnl']<ZERO for t in trades),
        breakevens=sum(t['pnl']==ZERO for t in trades),
        profit_factor=positive/negative if negative else None,
        mean_r=sum((t['net_r'] for t in trades),ZERO)/D(len(trades)) if trades else None,
        fees=sum((t['fees'] for t in trades),ZERO),exposure_pct=HUNDRED*D(occupied_count)/D(len(marks)),
        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_fisher_exits=sum(t['delayed_fisher_exit'] for t in trades),partial_close_proxies=sum(t['partial_close_proxy'] for t in trades),
        entry_slippage=sum((t['qty']*(t['entry']-t['entry_ref']) for t in trades),ZERO),
        exit_slippage=sum((t['qty']*(t['exit_ref']-t['exit']) for t in trades),ZERO),
        turnover=sum((t['qty']*(t['entry']+t['exit']) for t in trades),ZERO)/initial)
    endings={}
    for mark in marks:
        endings[dt.datetime.fromtimestamp(mark['ts']-1,dt.timezone.utc).year]=mark['equity']
    annual=[]
    prev=initial
    for year,balance in sorted(endings.items()):
        annual.append(dict(year=year,return_pct=HUNDRED*(balance/prev-ONE)))
        prev=balance
    flagged=[t for t in trades if t['crosses_gap'] or t['touches_noncanonical']]
    return dict(variant=variant,period=period,start_ts=start,end_ts=finish,fee=fee,slippage=slip,
        metrics=metrics,trades=trades,equity=marks,annual=annual,
        quality_exclusion_diagnostic=dict(removed_trades=len(flagged),
            retained_pnl=sum((t['pnl'] for t in trades if not(t['crosses_gap'] or t['touches_noncanonical'])),ZERO),
            scope='Original recorded quantities; not an executable avoidance rule or rebuilt account return'))


def buy_and_hold(rows,protocol,period):
    begin,end=map(epoch,protocol['periods'][period])
    selected=[b for b in rows if begin<=b['ts']<end]
    require(selected and selected[-1]['ts']+STEP==end,'Benchmark lacks period-end bar')
    fee,slip=costs_for(protocol,'primary')
    initial=decimal(protocol['initial_cash'])
    qty=initial/(selected[0]['open']*(ONE+slip)*(ONE+fee))
    peak=initial
    equity=[]
    for bar in selected:
        value=qty*bar['close']*(ONE-slip)*(ONE-fee)
        peak=max(peak,value)
        equity.append(dict(ts=bar['ts']+STEP,bar_ts=bar['ts'],equity=value,
                           drawdown_pct=HUNDRED*(peak-value)/peak))
    return dict(period=period,metrics=dict(return_pct=HUNDRED*(equity[-1]['equity']/initial-ONE),
        end_cash=equity[-1]['equity'],drawdown_pct=max(m['drawdown_pct'] for m in equity),
        exposure_pct=HUNDRED),equity=equity)


def first_opposite(trades, reference):
    return next((trade for trade in trades if trade['pnl']*reference<ZERO),None)


def example_selection(rows,runs):
    require(runs['primary_early']['trades'] and runs['primary_later']['trades'],'A chronological example is unavailable')
    early=runs['primary_early']['trades'][0]
    later=runs['primary_later']['trades'][0]
    opposite=first_opposite(runs['primary_later']['trades'],later['pnl'])
    require(opposite is not None,'No strictly opposite nonzero-sign example')
    return [dict(tag=tag,trade=trade,bars=[b for b in rows if trade['signal_bar_ts']-16*STEP<=b['ts']<=trade['exit_bar_ts']+3*STEP])
            for tag,trade in (('early',early),('later',later),('opposite',opposite))]


def toy_bar(slot,opening='100',high='106',low='95',close='101',atr='5',
            eligible=False,crossed=False,fisher_exit=False,canonical=True):
    ts=slot*STEP
    bar=normalize_bar(dict(ts=ts,open=D(opening),high=D(high),low=D(low),close=D(close),volume=ONE,
        timestamp_scale=1000,source_close_raw=(ts+STEP)*1000-(1 if canonical else 2)))
    bar.update(dict.fromkeys(INDICATOR_KEYS));bar.update(dict.fromkeys(FLAG_KEYS,False))
    bar.update(ema200=D(100),fisher=D(2),trigger=D(1),atr14=D(atr),eligible=eligible,
        fisher_cross=crossed,fisher_exit=fisher_exit)
    return bar


def toy_protocol(slots,fee='0',slip='0',holding=30,start_slot=0):
    return dict(periods={'toy':[utc(start_slot*STEP),utc(slots*STEP)]},initial_cash=10000,
        risk_fraction=D('.01'),holding_limit_intervals=holding,
        base_costs=dict(fee_each_side=D(fee),slippage_each_side=D(slip)),
        higher_costs=dict(fee_each_side=2*D(fee),slippage_each_side=2*D(slip)))


def raw_toys(medians):
    return [normalize_bar(toy_bar(j,opening=str(v),high=str(D(v)+1),low=str(D(v)-1),close=str(v)))for j,v in enumerate(medians)]


def run_synthetic_tests():
    tests=[]
    def check(name,condition):
        require(condition,'Synthetic failure: '+name)
        tests.append(name)
    signal=toy_bar(-1,eligible=True,crossed=True)
    check('Primary_above_EMA200_passes',qualifies(signal,'primary'))
    below=copy.deepcopy(signal);below['close']=D(100)
    check('EMA200_equality_is_excluded',not qualifies(below,'primary'))
    check('No_EMA_control_removes_only_trend_gate',qualifies(below,'no_ema'))
    below['eligible']=False
    check('No_EMA_control_keeps_common_warmup',not qualifies(below,'no_ema'))
    bars=[signal,toy_bar(0,fisher_exit=True),toy_bar(1,opening='102',high='110',low='80',close='85')]
    run=account_path(bars,toy_protocol(2),'primary','toy');t=run['trades'][0]
    check('Account_start_uses_immediately_prior_completed_signal',t['entry_ts']==0)
    check('Queued_Fisher_exit_at_open_precedes_later_low',t['reason']=='fisher_exit' and t['exit_ref']==D(102) and t['exit_precision']=='open')
    check('Exposure_excludes_existing_position_exited_at_open',run['metrics']['exposure_pct']==D(50))
    changed=copy.deepcopy(bars);changed[-1]['low']=D(1)
    check('Future_low_cannot_change_executed_open_exit',account_path(changed,toy_protocol(2),'primary','toy')['trades']==run['trades'])
    missing=account_path([signal,toy_bar(1),toy_bar(2)],toy_protocol(3),'primary','toy')
    check('Missing_next_open_cancels_entry',not missing['trades'] and missing['metrics']['canceled_missing_entry']==1)
    check('Missing_entry_is_not_resurrected_later',missing['metrics']['end_cash']==D(10000))
    bars=[signal,toy_bar(0,fisher_exit=True),toy_bar(1,opening='80',high='100',low='70',close='85')]
    t=account_path(bars,toy_protocol(2),'primary','toy')['trades'][0]
    check('Opening_stop_gap_precedes_queued_Fisher_exit',t['reason']=='stop_gap' and t['exit_ref']==D(80))
    bars=[signal]+[toy_bar(j,high='101',low='99',close='100')for j in range(31)]
    timed=account_path(bars,toy_protocol(31),'primary','toy');t=timed['trades'][0]
    check('Entry_interval_counts1_and30th_close_is_deadline',t['reason']=='time' and t['exit_event_ts']==30*STEP and t['holding_intervals']==30)
    stop_bars=copy.deepcopy(bars);stop_bars[30]['low']=D(89)
    t=account_path(stop_bars,toy_protocol(31),'primary','toy')['trades'][0]
    check('Intrabar_stop_precedes_same_close_time_exit',t['reason']=='stop' and t['exit_bar_ts']==29*STEP and t['exit_precision']=='within_4h')
    bars=[signal,toy_bar(0),toy_bar(3),toy_bar(4)]
    t=account_path(bars,toy_protocol(5,holding=2),'primary','toy')['trades'][0]
    check('Missed_time_deadline_uses_first_later_open',t['reason']=='time_delayed' and t['exit_event_ts']==3*STEP)
    check('Existing_stop_survives_missing_bars',t['stop']==D(90) and t['crosses_gap'])
    bars=[signal,toy_bar(0,fisher_exit=True),toy_bar(3),toy_bar(4)]
    t=account_path(bars,toy_protocol(5,holding=2),'primary','toy')['trades'][0]
    check('Queued_Fisher_exit_precedes_overdue_time',t['reason']=='fisher_exit' and t['delayed_fisher_exit'])
    bars=[signal,toy_bar(0,fisher_exit=True),toy_bar(3,opening='80',high='100',low='70',close='85'),toy_bar(4)]
    t=account_path(bars,toy_protocol(5,holding=2),'primary','toy')['trades'][0]
    check('Opening_gap_precedes_both_queued_and_overdue_time',t['reason']=='stop_gap')
    bars=[signal,toy_bar(0),toy_bar(1,canonical=False)]
    t=account_path(bars,toy_protocol(2),'primary','toy')['trades'][0]
    check('Survivor_liquidates_at_period_end_without_later_quotes',t['reason']=='period_end' and t['exit_event_ts']==2*STEP)
    check('Noncanonical_terminal_close_is_flagged_proxy',t['partial_close_proxy'] and t['touches_noncanonical'])
    bars=[signal,toy_bar(0,canonical=False)]
    t=account_path(bars,toy_protocol(1),'primary','toy')['trades'][0]
    check('Entry_bar_later_noncanonical_metadata_does_not_censor_open',t['entry_ts']==0 and t['touches_noncanonical'])
    try:account_path([signal,toy_bar(0)],toy_protocol(2),'primary','toy')
    except AuditError:tests.append('Missing_final_scheduled_bar_is_rejected')
    else:raise AuditError('Missing final bar silently accepted')
    bars=[signal,toy_bar(0,fisher_exit=True,eligible=False),toy_bar(1)]
    bars[1]['ema200']=None;bars[1]['atr14']=None
    t=account_path(bars,toy_protocol(2),'primary','toy')['trades'][0]
    check('Fisher_exit_does_not_need_entry_gate_EMA200_or_ATR',t['reason']=='fisher_exit')
    bars=[signal,toy_bar(0,fisher_exit=True),toy_bar(1,eligible=True,crossed=True),toy_bar(2)]
    out=account_path(bars,toy_protocol(3),'primary','toy')
    check('No_same_open_reentry_after_open_exit',len(out['trades'])==2 and out['trades'][1]['entry_ts']==2*STEP)
    cap_signal=toy_bar(-1,atr='.1',eligible=True,crossed=True)
    cap=account_path([cap_signal,toy_bar(0,high='101',low='99.9',close='100')],toy_protocol(1),'primary','toy')
    check('Cash_cap_prevents_leverage',cap['metrics']['cash_capped']==1 and cap['trades'][0]['qty']==D(100))
    check('Exact_zero_PnL_is_a_breakeven',cap['metrics']['breakevens']==1 and cap['trades'][0]['pnl']==ZERO)
    check('Zero_PnL_is_neither_win_nor_loss',cap['metrics']['wins']==0 and cap['metrics']['losses']==0)
    risky=account_path([signal,toy_bar(0,high='101',low='99',close='100')],toy_protocol(1,fee='.001',slip='.0005'),'primary','toy')
    trade=risky['trades'][0]
    check('Nominal_stop_budget_includes_both_cost_sides',trade['risk_cash']==D(100))
    check('Cash_identity_holds_with_costs',abs(risky['metrics']['end_cash']-D(10000)-trade['pnl'])<D('1e-35'))
    check('Positive_clip_threshold_equality_unchanged',clip_normalized(D('.99'))==D('.99'))
    check('Negative_clip_threshold_equality_unchanged',clip_normalized(D('-.99'))==D('-.99'))
    check('Positive_strict_clip_jumps_to999',clip_normalized(D('.99001'))==D('.999'))
    check('Negative_strict_clip_jumps_to_minus999',clip_normalized(D('-.99001'))==D('-.999'))
    check('Interior_not_clamped',clip_normalized(D('.989'))==D('.989'))
    flat=rebuild_indicators(raw_toys([100]*205))
    check('EMA200_first_index199',flat[198]['ema200']is None and flat[199]['ema200']==D(100))
    check('ATR14_first_index13',flat[12]['atr14']is None and flat[13]['atr14']==D(2))
    check('Flat10_has_no_defined_Fisher',flat[-1]['fisher']is None and flat[-1]['trigger']is None and flat[-1]['u']is None)
    check('Flat_Fisher_blocks_shared_entry',not flat[-1]['eligible'])
    prices=[D(100+j)for j in range(260)]
    rebuilt=rebuild_indicators(raw_toys(prices))
    initial_f=((ONE+D('.33'))/(ONE-D('.33'))).ln()/D(2)
    check('First_full10_window_Fisher_at_index9',rebuilt[8]['fisher']is None and abs(rebuilt[9]['fisher']-initial_f)<D('1e-46'))
    check('Seed_is_zero_prior_states_not_forced_first_F_zero',rebuilt[9]['u']==D('.33') and rebuilt[9]['fisher']!=ZERO)
    check('Window_extrema_are10_medians',rebuilt[9]['median_high10']==D(109) and rebuilt[9]['median_low10']==D(100))
    check('First_Trigger_at_index10',rebuilt[9]['trigger']is None and rebuilt[10]['trigger']==rebuilt[9]['fisher'])
    check('Trigger_is_previous_Fisher_not_average',all(rebuilt[j]['trigger']==rebuilt[j-1]['fisher']for j in range(10,len(rebuilt))))
    check('No_cross_without_previous_Trigger',not rebuilt[10]['fisher_cross'])
    check('Normalization_recursive_weight33_67',rebuilt[10]['u_raw']==D('.33')+D('.67')*D('.33'))
    check('Shared200_gate_first_index199',not rebuilt[198]['eligible']and rebuilt[199]['eligible'])
    for prefix in (9,10,11,35,200):
        check('Future_append_preserves_prefix_'+str(prefix),rebuild_indicators(raw_toys(prices[:prefix]))==rebuilt[:prefix])
    altered=raw_toys(prices)
    for row in altered:row['close']=row['low']
    changed=rebuild_indicators(altered)
    check('Fisher_input_is_median_not_close',all(a['fisher']==b['fisher']for a,b in zip(changed,rebuilt)))
    falling=rebuild_indicators(raw_toys(list(reversed(prices))))
    check('First_Fisher_negative_is_symmetric',abs(falling[9]['fisher']+rebuilt[9]['fisher'])<D('1e-46'))
    sequence=raw_toys([D(100+j)for j in range(30)]+[D(130)]*10+[D(131),D(132),D(131),D(130)])
    boundary=rebuild_indicators(sequence)
    check('Flat10_resets_recursive_Fisher',boundary[39]['fisher']is None and boundary[39]['trigger']is None)
    check('Flat10_keeps_ATR_history',boundary[39]['atr14']is not None)
    check('Postflat_Fisher_restarts_at_zero_states',abs(boundary[40]['fisher']-initial_f)<D('1e-46')and boundary[40]['u']==D('.33'))
    check('Postflat_Trigger_waits_next_consecutive_Fisher',boundary[40]['trigger']is None and boundary[41]['trigger']==boundary[40]['fisher'])
    check('Cross_does_not_bridge_flat_window',not boundary[40]['fisher_cross']and not boundary[41]['fisher_cross'])
    broken=raw_toys(prices);broken[40]['canonical']=False
    reset=rebuild_indicators(broken)
    check('Noncanonical_row_has_no_indicators',all(reset[40][k]is None for k in INDICATOR_KEYS))
    check('Fisher_reseeds_after_noncanonical_row',reset[49]['fisher']is None and reset[50]['fisher']is not None and reset[50]['trigger']is None)
    check('Entry200_gate_reseeds_after_reset',not reset[239]['eligible']and reset[240]['eligible'])
    gap=rebuild_indicators(raw_toys(prices)[:40]+raw_toys(prices)[41:])
    check('Missing_bar_resets_Fisher_EMA_ATR',all(gap[40][k]is None for k in ('fisher','trigger','ema200','atr14')))
    check('Postgap_first_TR_has_no_price_bridge',gap[53]['atr14']==D(2))
    after_long_flat=rebuild_indicators(raw_toys([D(100+j)for j in range(220)]+[D(320)]*10+[D(321),D(322),D(321)]))
    check('Flat10_does_not_reset_EMA200',after_long_flat[229]['fisher']is None and after_long_flat[229]['ema200']is not None)
    check('Postflat_first_Trigger_unavailable_blocks_entry',not after_long_flat[230]['eligible']and after_long_flat[230]['trigger']is None)
    check('Postflat_second_Fisher_still_lacks_previous_Trigger',not after_long_flat[231]['eligible']and after_long_flat[231]['trigger']is not None)
    check('Postflat_third_Fisher_restores_shared_entry_readiness',after_long_flat[232]['eligible'])
    signs=[dict(pnl=D('0')),dict(pnl=D('1e-40')),dict(pnl=D('0')),dict(pnl=D('-1e-40')),dict(pnl=D('-2'))]
    check('Opposite_example_excludes_zeros_and_keeps_tiny_negative_sign',first_opposite(signs,D(1))is signs[3])
    check('Opposite_example_follows_reference_negative_sign',first_opposite(signs,D(-1))is signs[1])
    check('Zero_reference_has_no_opposite_nonzero_sign',first_opposite(signs,ZERO)is None)
    check('Previous_Fisher_trigger_equality_permits_cross',pair_cross(D(1),D(1),D(2),D(1)))
    check('Current_Fisher_trigger_equality_rejects_cross',not pair_cross(D(0),D(1),D(1),D(1)))
    check('Already_above_trigger_is_no_fresh_cross',not pair_cross(D(2),D(1),D(3),D(2)))
    check('Missing_previous_Fisher_blocks_cross',not pair_cross(None,D(1),D(2),D(1)))
    check('Missing_current_Trigger_blocks_cross',not pair_cross(D(0),D(1),D(2),None))
    check('No_cross_means_no_entry',not qualifies(toy_bar(0,eligible=True,crossed=False),'primary'))
    bad=toy_bar(-1,atr='60',eligible=True,crossed=True)
    invalid=account_path([bad,toy_bar(0)],toy_protocol(1),'primary','toy')
    check('Nonpositive_fixed_stop_rejects_entry',not invalid['trades']and invalid['metrics']['rejected_entry']==1)
    bad=toy_bar(-1,atr='.01',eligible=True,crossed=True)
    invalid=account_path([bad,toy_bar(0)],toy_protocol(1,slip='.1'),'primary','toy')
    check('Stop_not_below_raw_open_rejects_entry',not invalid['trades']and invalid['metrics']['rejected_entry']==1)
    return tests


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--protocol',type=Path)
    parser.add_argument('--evidence',type=Path)
    parser.add_argument('--raw-dir',type=Path)
    parser.add_argument('--synthetic-only',action='store_true')
    parser.add_argument('--report',type=Path,default=Path(__file__).with_name('independent-verification.json'))
    args=parser.parse_args()
    report=dict(status='failed',decimal_precision=50,
        method='Separate Decimal50 segment-batch Fisher indicators and scheduled-clock account replay, adapted from the existing independent-account harness; no main replay imports or execution',
        checker_sha256=digest(Path(__file__)),
        tolerances_absolute={k:str(v)for k,v in TOLERANCES.items()},
        limitations=['Pinned previously retained archive bytes and local checksum sidecars are checked; no independent provider download or origin authentication is claimed.',
            'H4 range stops identify an interval; missing price paths and noncanonical close liquidation proxies remain limitations.',
            'Exposure is the fraction of observed H4 intervals occupied after opening decisions, not exact wall-clock exposure.',
            'Synthetic execution fixtures inject completed-close indicator states to isolate event priorities; separate indicator fixtures reconstruct prices, seeds and resets.'])
    comparison=Comparison()
    try:
        report['synthetic_tests']=[dict(name=name,status='passed')for name in run_synthetic_tests()]
        if args.synthetic_only:
            report['status']='passed'
            report['scope']='Synthetic fixtures only; no historical archives, evidence, indicator outcomes or account outcomes read or calculated'
        else:
            require(args.protocol and args.evidence and args.raw_dir,'Historical verification requires --protocol, --evidence and --raw-dir')
            protocol_hash=digest(args.protocol)
            require(protocol_hash==FROZEN_SHA256,'Protocol differs from frozen SHA256')
            protocol=read_json(args.protocol)
            require(protocol['status']=='frozen_before_first_calculation','Protocol is not frozen')
            require(protocol['parameters']['fisher_length']==10 and protocol['parameters']['ema_length']==200 and protocol['parameters']['trigger_lag']==1,'Unexpected fixed parameters')
            evidence=read_json(args.evidence)
            report['protocol_sha256']=protocol_hash
            report['evidence_sha256']=digest(args.evidence)
            comparison.compare(protocol,evidence['protocol'],'protocol')
            comparison.compare(protocol_hash,evidence['protocol_sha256'],'protocol_sha256')
            manifest=protocol['source_manifest']
            require(len(manifest)==79 and len({item['file']for item in manifest})==79,'Frozen source manifest must contain79 distinct ZIPs')
            comparison.compare(manifest,evidence['data_quality']['sources'],'pinned_source_manifest')
            raw,archives=load_original_rows(args.raw_dir,manifest,protocol)
            report['source_verification']=dict(mode='all79 original ZIP/CSV rows',archives=len(archives),
                archive_rows=sum(x['rows']for x in archives),all_pinned_hashes_sidecar_digests_filenames_and_CRCs_passed=True)
            require(raw[0]['ts']==epoch(protocol['warmup_start']),'Wrong warmup start')
            require(raw[-1]['ts']+STEP==max(epoch(x[1])for x in protocol['periods'].values()),'Wrong final source interval')
            independent_quality=quality(raw,manifest)
            comparison.compare(independent_quality,evidence['data_quality'],'data_quality')
            rows=rebuild_indicators(raw)
            comparison.compare(rows,evidence['bars'],'bars')
            report['data_validation']=dict(all_rows_compared=len(rows),first_open_utc=utc(rows[0]['ts']),
                last_close_utc=utc(rows[-1]['ts']+STEP),missing_scheduled_intervals=independent_quality['missing_bars'],
                noncanonical_source_closes=len(independent_quality['noncanonical_closes']),
                indicator_fields=list(INDICATOR_KEYS+FLAG_KEYS))
            runs={v+'_'+p:account_path(rows,protocol,v,p)for v,p in RUNS}
            comparison.compare(runs,evidence['runs'],'runs')
            benchmark={p:buy_and_hold(rows,protocol,p)for p in protocol['periods']}
            comparison.compare(benchmark,evidence['buy_hold'],'buy_hold')
            comparison.compare(example_selection(rows,runs),evidence['examples'],'examples')
            report['replayed_accounts']={key:dict(trades=len(run['trades']),close_marks=len(run['equity']),
                end_cash_USDT=str(run['metrics']['end_cash']),cash_identity_absolute_error_USDT=str(abs(run['metrics']['end_cash']-
                decimal(protocol['initial_cash'])-sum((t['pnl']for t in run['trades']),ZERO))))for key,run in runs.items()}
            report['additional_checks']=dict(restarted_buy_hold_paths=len(benchmark),protocol_selected_examples=3,
                annual_returns='compared',source_and_protocol_provenance='compared',
                every_trade_metric_equity_drawdown_and_quality_exclusion_field='compared',frozen_rules_changed=False)
            report['status']='passed'if not comparison.failures else'failed'
    except Exception as error:
        report['fatal_error']=type(error).__name__+': '+str(error)
    report['comparison']=dict(numeric_values_compared=comparison.numeric_count,exact_values_compared=comparison.exact_count,
        failures=comparison.failures,failure_samples=comparison.samples,
        maximum_absolute_errors={k:str(v)for k,v in comparison.max_error.items()},maximum_error_locations=comparison.max_error_at)
    report['checked_at_utc']=dt.datetime.now(dt.timezone.utc).isoformat()
    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(dict(status=report['status'],report=str(args.report),synthetic_tests=len(report.get('synthetic_tests',[])),
        failures=comparison.failures,fatal_error=report.get('fatal_error')),indent=2))
    return 0 if report['status']=='passed' else 1

if __name__=='__main__':
    sys.exit(main())
