#!/usr/bin/env python3
"""Independent Decimal(40) audit of the frozen ETHUSDT Williams %R / EMA200 cash-account study.

Uses only the Python standard library. It neither imports nor executes the main
replay. The execution model advances a scheduled clock, treats open and close as
separate phases, and rebuilds every indicator from source prices. Original ZIPs
are optional; when supplied, all manifest hashes, CHECKSUMs, CRCs and source rows
are checked before the reconstruction.

Example:
  python eth-wr-independent-check.py --evidence eth-wr-evidence.json \
      --protocol eth-wr-protocol.json --raw-dir /path/to/original/ZIPs

The JSON report is written beside this checker unless --report is supplied.
Absolute tolerances: 0.000001 USDT for account amounts, 0.00000001 for prices,
indicators and dimensionless metrics, and 0.000000000001 ETH for quantities.
Integer counts, event types, timestamps, validity and quality flags are exact.
"""

import argparse
from collections import Counter, deque
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 = 40
D = Decimal
ZERO = D(0)
ONE = D(1)
HUNDRED = D(100)
STEP = 14400
FROZEN_SHA256 = "24fa3998815c64ddd2f1f2ac4e630572970cad6d51916a3791955faaa3a6c15c"
TOLERANCES = {
    "account_USDT": D("0.000001"),
    "price_indicator_or_metric": D("0.00000001"),
    "quantity_ETH": D("0.000000000001"),
}
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 = (
    ("primary", "full"), ("primary", "early"), ("primary", "later"),
    ("no_ema", "full"), ("no_ema", "early"), ("no_ema", "later"),
    ("zero_cost", "full"), ("higher_cost", "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")
    for key in ("high", "low", "close"):
        scaled = bar[key] * D(100000000)
        require(scaled == scaled.to_integral_value(), "Source price exceeds frozen eight-decimal scale")
        bar[key + "_int"] = int(scaled)
    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(pieces and pieces[0].lower() == archive_hash,
                "Published CHECKSUM mismatch for " + name)
        if len(pieces) > 1:
            require(Path(pieces[1].lstrip("*")).name == 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])
                    possible_scales = [scale for scale in (1000, 1000000)
                                       if source_open % scale == 0
                                       and lower <= source_open // scale < upper]
                    require(len(possible_scales) == 1, "Ambiguous source timestamp unit")
                    scale = possible_scales[0]
                    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 rebuild_indicators(rows):
    """Independent bounded OHLC windows, rational threshold tests and Decimal states."""
    highs = deque(maxlen=14)
    lows = deque(maxlen=14)
    seed_closes = []
    seed_trs = []
    atr = None
    ema = None
    alpha = D(2) / D(201)
    previous_close = None
    previous_ratio = None
    previous_timestamp = None
    count = 0
    output = []
    for raw in rows:
        bar = dict(raw)
        interrupted = previous_timestamp is not None and raw["ts"] != previous_timestamp + STEP
        if interrupted or not raw["canonical"]:
            highs.clear(); lows.clear()
            seed_closes = []; seed_trs = []
            atr = None; ema = None
            previous_close = None; previous_ratio = None
            count = 0
        bar.update(wr_numerator=None, wr_denominator=None, wr=None, ema200=None,
                   atr14=None, eligible=False, recovery_cross=False, exit_level=False)
        if raw["canonical"]:
            movement = raw["high"] - raw["low"]
            if previous_close is not None:
                movement = max(movement, abs(raw["high"] - previous_close),
                               abs(raw["low"] - previous_close))
            count += 1
            highs.append(raw["high_int"]); lows.append(raw["low_int"])
            if atr is None:
                seed_trs.append(movement)
                if len(seed_trs) == 14:
                    atr = sum(seed_trs, ZERO) / D(14)
            else:
                atr += (movement - atr) / D(14)
            if ema is None:
                seed_closes.append(raw["close"])
                if len(seed_closes) == 200:
                    ema = sum(seed_closes, ZERO) / D(200)
            else:
                ema += alpha * (raw["close"] - ema)
            current_ratio = None
            if len(highs) == 14:
                ceiling = max(highs)
                floor = min(lows)
                denominator = ceiling - floor
                if denominator != 0:
                    numerator = -100 * (ceiling - raw["close_int"])
                    current_ratio = (numerator, denominator)
                    bar["wr_numerator"] = numerator
                    bar["wr_denominator"] = denominator
                    bar["wr"] = D(numerator) / D(denominator)
                    bar["exit_level"] = numerator >= -20 * denominator
                    if previous_ratio is not None:
                        pnum, pden = previous_ratio
                        bar["recovery_cross"] = (pnum <= -80 * pden
                            and numerator > -80 * denominator
                            and numerator < -20 * denominator)
            bar["ema200"] = ema
            bar["atr14"] = atr
            bar["eligible"] = (count >= 200 and atr is not None and atr > ZERO
                               and current_ratio is not None and previous_ratio is not None)
            previous_close = raw["close"]
            previous_ratio = current_ratio
        previous_timestamp = raw["ts"]
        output.append(bar)
    return output


def qualifies(bar, variant):
    return (bar is not None and bar["eligible"] and bar["recovery_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):
    """Replay a scheduled clock, with opening execution preceding range/close use."""
    start, finish = map(epoch, protocol["periods"][period])
    by_time = {bar["ts"]: bar for bar in rows}
    observed = [bar for bar in rows if start <= bar["ts"] < finish]
    require(observed, "Empty study period " + period)
    initial = decimal(protocol["initial_cash"])
    fee, slip = costs_for(protocol, variant)
    cash = initial
    peak = initial
    risk_fraction = decimal(protocol["risk_fraction"])
    position = None
    queued_entry = None
    queued_exit_at = None
    previous = by_time.get(start - STEP)
    if qualifies(previous, variant):
        queued_entry = previous
    trades = []
    marks = []
    exposure = 0
    capped = 0
    canceled = 0
    rejected = 0

    def liquidate(bar, reference, reason, phase):
        nonlocal cash, position, queued_exit_at
        sale_price = reference * (ONE - slip)
        sale_notional = position["qty"] * sale_price
        exit_fee = sale_notional * fee
        proceeds = sale_notional - exit_fee
        entry_cost = position["_entry_cost"]
        pnl = proceeds - entry_cost
        cash += proceeds
        public = {key: value for key, value in position.items() if not key.startswith("_")}
        close_phase = phase == "close"
        public.update(
            exit_bar_ts=bar["ts"], exit_event_ts=bar["ts"] + (STEP if close_phase else 0),
            exit_precision=phase, exit_ref=reference, exit=sale_price, reason=reason,
            fees=position["_entry_fee"] + exit_fee, pnl=pnl,
            net_r=pnl / position["risk_cash"],
            holding_intervals=1 + (bar["ts"] - position["entry_ts"]) // STEP,
            delayed_wr_exit=(reason == "wr_exit" and queued_exit_at is not None
                             and bar["ts"] > queued_exit_at),
            partial_close_proxy=close_phase and not bar["canonical"],
        )
        trades.append(public)
        position = None
        queued_exit_at = None
        require(abs(cash - initial - sum((item["pnl"] for item in trades), ZERO))
                < D("1e-25"), "Cash ledger does not reconcile after liquidation")

    for opening in range(start, finish, STEP):
        bar = by_time.get(opening)
        if bar is None:
            if queued_entry is not None and queued_entry["ts"] + STEP == opening:
                canceled += 1
                queued_entry = None
            if position is not None:
                position["crosses_gap"] = True
            continue

        occupied_at_open = position is not None
        # No current-bar close, Williams reading, ATR, or close-time metadata gates this entry.
        if queued_entry is not None:
            require(position is None, "Attempt to fund overlapping positions")
            require(queued_entry["ts"] + STEP == opening, "A missing entry was entered late")
            fill = bar["open"] * (ONE + slip)
            stop = fill - D(2) * queued_entry["atr14"]
            net_at_stop = stop * (ONE - slip) * (ONE - fee)
            entry_per_unit = fill * (ONE + fee)
            loss_per_unit = entry_per_unit - net_at_stop
            if not (ZERO < stop < bar["open"] and loss_per_unit > ZERO):
                rejected += 1
            else:
                risk_quantity = cash * risk_fraction / loss_per_unit
                funding_quantity = cash / entry_per_unit
                quantity = min(risk_quantity, funding_quantity)
                is_capped = funding_quantity < risk_quantity
                before = cash
                notional = quantity * fill
                entry_fee = notional * fee
                total_entry_cost = notional + entry_fee
                cash -= total_entry_cost
                require(cash >= -D("1e-30"), "Entry borrowed account cash")
                if abs(cash) < D("1e-30"):
                    cash = ZERO
                require(quantity * loss_per_unit <= before * risk_fraction + D("1e-30"),
                        "Entry exceeded the frozen cash-risk budget")
                position = {
                    "signal_bar_ts": queued_entry["ts"],
                    "signal_ts": queued_entry["ts"] + STEP,
                    "entry_ts": opening, "entry_ref": bar["open"], "entry": fill,
                    "stop": stop, "qty": quantity, "risk_cash": quantity * loss_per_unit,
                    "cash_before": before, "cash_capped": is_capped,
                    "signal_wr": queued_entry["wr"],
                    "signal_ema200": queued_entry["ema200"],
                    "signal_atr14": queued_entry["atr14"],
                    "crosses_gap": False, "touches_noncanonical": False,
                    "_entry_cost": total_entry_cost, "_entry_fee": entry_fee,
                    "_deadline": opening + int(protocol["holding_limit_intervals"]) * STEP,
                }
                occupied_at_open = True
                capped += int(is_capped)
            queued_entry = None

        if position is not None:
            if not bar["canonical"]:
                # Retrospective quality flag only; it never cancels an opening fill.
                position["touches_noncanonical"] = True
            # Open phase: no later high, low or close has been consulted.
            if bar["open"] <= position["stop"]:
                liquidate(bar, bar["open"], "stop_gap", "open")
            elif queued_exit_at is not None:
                liquidate(bar, bar["open"], "wr_exit", "open")
            elif opening >= position["_deadline"]:
                liquidate(bar, bar["open"], "time_delayed", "open")

        if position is not None:
            # Range and close phase, reached only when no open-phase fill occurred.
            if bar["low"] <= position["stop"]:
                liquidate(bar, position["stop"], "stop", "within_4h")
            elif opening + STEP >= position["_deadline"]:
                liquidate(bar, bar["close"], "time", "close")
            elif opening == observed[-1]["ts"]:
                liquidate(bar, bar["close"], "period_end", "close")
            elif bar["exit_level"]:
                queued_exit_at = opening + STEP

        exposure += int(occupied_at_open)
        liquidation_value = (position["qty"] * bar["close"] * (ONE - slip) * (ONE - fee)
                             if position is not None else ZERO)
        marked = cash + liquidation_value
        peak = max(peak, marked)
        marks.append({"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):
            queued_entry = bar

    require(position is None, "No observed period-end liquidation quote")
    require(abs(cash - initial - sum((item["pnl"] for item in trades), ZERO))
            < D("1e-25"), "Terminal cash identity failed")
    pnl_positive = sum((item["pnl"] for item in trades if item["pnl"] > ZERO), ZERO)
    pnl_negative = -sum((item["pnl"] for item in trades if item["pnl"] < ZERO), ZERO)
    metrics = {
        "return_pct": HUNDRED * (cash / initial - ONE), "end_cash": cash,
        "drawdown_pct": max(mark["drawdown_pct"] for mark in marks),
        "trades": len(trades), "wins": sum(item["pnl"] > ZERO for item in trades),
        "losses": sum(item["pnl"] < ZERO for item in trades),
        "profit_factor": pnl_positive / pnl_negative if pnl_negative else None,
        "mean_r": (sum((item["net_r"] for item in trades), ZERO) / D(len(trades))
                   if trades else None),
        "fees": sum((item["fees"] for item in trades), ZERO),
        "exposure_pct": HUNDRED * D(exposure) / D(len(marks)),
        "cash_capped": capped, "canceled_missing_entry": canceled, "rejected_entry": rejected,
        "gap_trades": sum(item["crosses_gap"] for item in trades),
        "noncanonical_trades": sum(item["touches_noncanonical"] for item in trades),
        "delayed_wr_exits": sum(item["delayed_wr_exit"] for item in trades),
        "partial_close_proxies": sum(item["partial_close_proxy"] for item in trades),
        "entry_slippage": sum((item["qty"] * (item["entry"] - item["entry_ref"])
                                for item in trades), ZERO),
        "exit_slippage": sum((item["qty"] * (item["exit_ref"] - item["exit"])
                               for item in trades), ZERO),
        "turnover": sum((item["qty"] * (item["entry"] + item["exit"])
                         for item in trades), ZERO) / initial,
    }
    year_ends = {}
    for mark in marks:
        year_ends[dt.datetime.fromtimestamp(mark["ts"] - 1, dt.timezone.utc).year] = mark["equity"]
    previous_balance = initial
    annual = []
    for year, balance in sorted(year_ends.items()):
        annual.append({"year": year, "return_pct": HUNDRED * (balance / previous_balance - ONE)})
        previous_balance = balance
    flagged = [item for item in trades if item["crosses_gap"] or item["touches_noncanonical"]]
    return {
        "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": {
            "removed_trades": len(flagged),
            "retained_pnl": sum((item["pnl"] for item in trades
                                 if not (item["crosses_gap"] or item["touches_noncanonical"])), ZERO),
            "scope": "Original recorded quantities; not an executable avoidance rule or rebuilt account return",
        },
    }


def buy_and_hold(rows, protocol, period):
    start, end = map(epoch, protocol["periods"][period])
    selected = [bar for bar in rows if start <= bar["ts"] < end]
    fee, slip = costs_for(protocol, "primary")
    initial = decimal(protocol["initial_cash"])
    quantity = initial / (selected[0]["open"] * (ONE + slip) * (ONE + fee))
    peak = initial
    marks = []
    for bar in selected:
        value = quantity * bar["close"] * (ONE - slip) * (ONE - fee)
        peak = max(peak, value)
        marks.append({"ts": bar["ts"] + STEP, "bar_ts": bar["ts"], "equity": value,
                      "drawdown_pct": HUNDRED * (peak - value) / peak})
    return {"period": period, "metrics": {
        "return_pct": HUNDRED * (marks[-1]["equity"] / initial - ONE),
        "end_cash": marks[-1]["equity"],
        "drawdown_pct": max(mark["drawdown_pct"] for mark in marks),
        "exposure_pct": 100,
    }, "equity": marks}


def example_selection(rows, runs):
    early = next(iter(runs["primary_early"]["trades"]), None)
    later = next(iter(runs["primary_later"]["trades"]), None)
    opposite = (next((item for item in runs["primary_later"]["trades"]
                     if item["pnl"] * later["pnl"] < ZERO), None)
                if later is not None and later["pnl"] != ZERO else None)
    result = []
    for label, trade in (("early", early), ("later", later), ("opposite", opposite)):
        if trade is None:
            result.append({"tag": label, "trade": None, "bars": [], "available": False})
            continue
        chart_rows = [bar for bar in rows
                      if trade["signal_bar_ts"] - 20 * STEP <= bar["ts"]
                      <= trade["exit_bar_ts"] + 3 * STEP]
        result.append({"tag": label, "trade": trade, "bars": chart_rows})
    return result


def toy_bar(slot, opening="100", high="106", low="95", close="101", wr="-50",
            atr="5", eligible=False, crossed=False, canonical=True, ema="90"):
    timestamp = slot * STEP
    bar = normalize_bar({
        "ts": timestamp, "open": D(opening), "high": D(high), "low": D(low),
        "close": D(close), "volume": ONE, "timestamp_scale": 1000,
        "source_close_raw": (timestamp + STEP) * 1000 - (1 if canonical else 2),
    })
    value = None if wr is None else D(wr)
    denominator = 100000000 if value is not None else None
    numerator = int(value * denominator) if value is not None else None
    bar.update(wr_numerator=numerator, wr_denominator=denominator, wr=value,
               ema200=D(ema), atr14=D(atr), eligible=eligible,
               recovery_cross=crossed, exit_level=value is not None and value >= D(-20))
    return bar


def toy_protocol(slots, fee="0", slip="0", holding=30):
    return {
        "periods": {"toy": [utc(0), utc(slots * STEP)]}, "initial_cash": 10000,
        "risk_fraction": D("0.01"), "holding_limit_intervals": holding,
        "base_costs": {"fee_each_side": D(fee), "slippage_each_side": D(slip)},
    }


def run_synthetic_tests():
    results = []
    signal = toy_bar(-1, eligible=True, crossed=True)

    bars = [signal, toy_bar(0, wr="-20"),
            toy_bar(1, opening="102", high="110", low="80", close="85")]
    run = account_path(bars, toy_protocol(2), "primary", "toy")
    trade = run["trades"][0]
    require(trade["reason"] == "wr_exit" and trade["exit_ref"] == D("102")
            and trade["exit_precision"] == "open", "Queued exit was displaced by a later low")
    altered = copy.deepcopy(bars)
    altered[-1]["low"] = D("20")
    require(account_path(altered, toy_protocol(2), "primary", "toy")["trades"] == run["trades"],
            "Later low changed an already executed opening sale")
    results.append("WR_level_exit_at_exact_minus20_precedes_and_is_invariant_to_later_low")

    run = account_path([signal, toy_bar(1), toy_bar(2)], toy_protocol(3), "primary", "toy")
    require(not run["trades"] and run["metrics"]["canceled_missing_entry"] == 1
            and run["metrics"]["end_cash"] == D(10000), "Missing scheduled entry was not canceled")
    results.append("missing_scheduled_entry_is_canceled_without_late_fill")

    bars = [signal, toy_bar(0, wr="-10"),
            toy_bar(1, opening="80", high="100", low="70", close="85")]
    trade = account_path(bars, toy_protocol(2), "primary", "toy")["trades"][0]
    require(trade["reason"] == "stop_gap" and trade["exit_ref"] == D("80"),
            "Stop gap did not precede queued WR exit")
    results.append("stop_gap_has_priority_over_queued_WR_exit")

    bars = [signal] + [toy_bar(slot, high="101", low="99", close="100") for slot in range(31)]
    trade = account_path(bars, toy_protocol(31), "primary", "toy")["trades"][0]
    require(trade["reason"] == "time" and trade["exit_bar_ts"] == 29 * STEP
            and trade["exit_event_ts"] == 30 * STEP and trade["holding_intervals"] == 30,
            "Holding limit failed to count entry interval as one")
    results.append("surviving_30th_scheduled_close_counts_entry_interval_as_one")

    bars = [signal] + [toy_bar(slot, high="101", low="99", close="100") for slot in range(29)]
    bars.append(toy_bar(30, opening="102", high="110", low="80", close="85"))
    trade = account_path(bars, toy_protocol(31), "primary", "toy")["trades"][0]
    require(trade["reason"] == "time_delayed" and trade["exit_precision"] == "open"
            and trade["exit_ref"] == D("102") and trade["crosses_gap"],
            "Missed deadline failed to liquidate at first observed open before its low")
    results.append("missing_30th_interval_delays_to_first_observed_open")
    bars[-1] = toy_bar(30, opening="80", high="110", low="70", close="85")
    trade = account_path(bars, toy_protocol(31), "primary", "toy")["trades"][0]
    require(trade["reason"] == "stop_gap", "Stop gap failed to precede missed deadline")
    results.append("stop_gap_has_priority_over_missed_time_deadline")

    bars = [signal, toy_bar(0, wr="0"), toy_bar(2, opening="102", high="110", low="95", wr=None)]
    trade = account_path(bars, toy_protocol(3), "primary", "toy")["trades"][0]
    require(trade["reason"] == "wr_exit" and trade["delayed_wr_exit"] and trade["crosses_gap"],
            "A queued WR exit did not survive a missing scheduled open or unavailable later value")
    results.append("queued_WR_exit_survives_missing_open_and_unavailable_later_value")

    bars = [signal, toy_bar(0, low="85", close="100", wr=None, canonical=False)]
    trade = account_path(bars, toy_protocol(1), "primary", "toy")["trades"][0]
    require(trade["entry_ts"] == 0 and trade["reason"] == "stop"
            and trade["touches_noncanonical"], "Later close metadata censored an available opening")
    results.append("noncanonical_entry_close_metadata_never_censors_available_open")

    bars = [signal, toy_bar(0, high="101", low="99", close="100", wr=None, canonical=False)]
    trade = account_path(bars, toy_protocol(1), "primary", "toy")["trades"][0]
    require(trade["reason"] == "period_end" and trade["partial_close_proxy"]
            and trade["touches_noncanonical"], "Noncanonical close liquidation was not flagged as a proxy")
    results.append("noncanonical_scheduled_period_close_is_flagged_proxy")

    tiny_signal = toy_bar(-1, atr="0.01", eligible=True, crossed=True)
    run = account_path([tiny_signal, toy_bar(0)], toy_protocol(1, slip="0.0005"), "primary", "toy")
    require(not run["trades"] and run["metrics"]["rejected_entry"] == 1,
            "Stop at or above raw opening was accepted")
    results.append("stop_must_be_positive_and_strictly_below_raw_open")

    cap_signal = toy_bar(-1, atr="0.04", eligible=True, crossed=True)
    bars = [cap_signal, toy_bar(0, high="101", low="100", close="100", wr="-10"),
            toy_bar(1, high="101", low="100", close="100")]
    run = account_path(bars, toy_protocol(2, fee="0.001", slip="0.0005"), "primary", "toy")
    trade = run["trades"][0]
    require(trade["cash_capped"] and trade["risk_cash"] < D(100), "Cash funding cap did not bind")
    require(abs(trade["qty"] * trade["entry"] * D("1.001") - D(10000)) < D("1e-30"),
            "Cash cap did not include the entry fee")
    require(abs(run["metrics"]["end_cash"] - D(10000) - trade["pnl"]) < D("1e-25"),
            "Fee-inclusive cash and realized P&L disagree")
    results.append("cash_cap_includes_entry_fee_and_net_cash_ledger_reconciles")

    # Price-derived indicators, independently of the injected chronology fixtures.
    raw = [toy_bar(slot, high="110", low="90", close="100") for slot in range(410)]
    raw[209]["source_close_raw"] -= 123
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[199]["eligible"] and rebuilt[208]["eligible"], "Initial 200-bar gate failed")
    require(not rebuilt[209]["canonical"] and all(rebuilt[209][field] is None
            for field in ("wr", "ema200", "atr14", "wr_numerator", "wr_denominator")),
            "Malformed close retained indicator values")
    require(not rebuilt[408]["eligible"] and rebuilt[409]["eligible"], "200-bar restart gate failed")
    require(rebuilt[222]["atr14"] is None and rebuilt[223]["atr14"] == D(20),
            "ATR did not seed from fourteen post-reset true ranges")
    require(rebuilt[222]["wr"] is None and rebuilt[223]["wr"] == D(-50),
            "WR did not require a new fourteen-bar range")
    results.append("noncanonical_close_clears_and_restarts_14_and200_indicator_gates")

    raw = [toy_bar(slot, high="1001", low="999", close="1000", opening="1000")
           for slot in range(200)]
    raw += [toy_bar(slot, high="110", low="90", close="100") for slot in range(201, 401)]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(not rebuilt[200]["eligible"] and rebuilt[213]["atr14"] == D(20)
            and rebuilt[-1]["eligible"], "Missing observation was bridged in indicators")
    prefix = rebuild_indicators([normalize_bar(bar) for bar in raw[:220]])
    require(prefix == rebuilt[:220], "Future rows changed previously completed indicators")
    results.append("missing_bar_reset_and_indicator_prefix_future_invariance")

    # Exact rational equality at -80: recovery can first become eligible at candle200.
    raw = [toy_bar(slot, opening="95", high="110", low="90", close="100")
           for slot in range(198)]
    raw += [toy_bar(198, opening="95", high="110", low="90", close="94"),
            toy_bar(199, opening="95", high="110", low="90", close="95")]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[198]["wr"] == D(-80) and not rebuilt[198]["eligible"]
            and rebuilt[199]["wr"] == D(-75) and rebuilt[199]["recovery_cross"]
            and rebuilt[199]["eligible"], "Previous199/current200 gate or equality at -80 failed")
    require(qualifies(rebuilt[199], "no_ema"), "No-EMA control imposed a separate gate")
    results.append("exact_minus80_previous_equality_and_current200_prior199_gate")

    raw[-1] = toy_bar(199, opening="95", high="110", low="90", close="94")
    equal = rebuild_indicators([normalize_bar(bar) for bar in raw])[-1]
    require(equal["wr"] == D(-80) and not equal["recovery_cross"], "Current=-80 incorrectly crossed")
    raw[-1] = toy_bar(199, opening="95", high="110", low="90", close="106")
    upper = rebuild_indicators([normalize_bar(bar) for bar in raw])[-1]
    require(upper["wr"] == D(-20) and upper["exit_level"] and not upper["recovery_cross"],
            "Fast recovery directly to exit threshold was accepted")
    results.append("current_minus80_is_not_recovery_and_current_minus20_is_exit_not_entry")

    # Flat ranges make WR unavailable without resetting existing EMA or ATR state.
    raw = [toy_bar(slot, opening="100", high="110", low="90", close="100")
           for slot in range(200)]
    raw += [toy_bar(slot, opening="100", high="100", low="100", close="100")
            for slot in range(200, 214)]
    raw += [toy_bar(214, opening="100", high="110", low="90", close="102"),
            toy_bar(215, opening="100", high="110", low="90", close="103")]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[213]["wr"] is None and rebuilt[213]["wr_numerator"] is None
            and rebuilt[213]["wr_denominator"] is None and rebuilt[213]["ema200"] == D(100)
            and rebuilt[213]["atr14"] > ZERO, "Flat range reset or invented WR")
    require(not rebuilt[214]["eligible"] and not rebuilt[214]["recovery_cross"]
            and rebuilt[215]["eligible"], "Crossing bridged an unavailable previous reading")
    results.append("zero_range_makes_WR_unavailable_without_reset_or_crossing_bridge")

    # EMA is seeded exactly once, then recursively updated rather than recomputed SMA.
    raw = [toy_bar(slot, opening="100", high="110", low="90", close="100")
           for slot in range(200)]
    raw.append(toy_bar(200, opening="100", high="120", low="90", close="110"))
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[198]["ema200"] is None and rebuilt[199]["ema200"] == D(100)
            and abs(rebuilt[200]["ema200"] - (D(100) + D(20) / D(201))) < D("1e-35"),
            "EMA200 seed or recursive alpha was incorrect")
    results.append("EMA200_arithmetic_seed_then_alpha2over201_recursive_update")

    # A missing final interval still uses the explicitly declared last observed close.
    bars = [signal, toy_bar(0, high="101", low="99", close="100")]
    trade = account_path(bars, toy_protocol(2), "primary", "toy")["trades"][0]
    require(trade["reason"] == "period_end" and trade["exit_event_ts"] == STEP,
            "Unavailable terminal quote invented a close at the nominal period end")
    results.append("period_end_uses_last_observed_close_and_its_actual_event_timestamp")
    return results


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--evidence", type=Path, required=True)
    parser.add_argument("--protocol", type=Path, required=True)
    parser.add_argument("--raw-dir", type=Path)
    parser.add_argument("--report", type=Path,
                        default=Path(__file__).with_name("eth-wr-independent-verification.json"))
    args = parser.parse_args()
    report = {
        "status": "failed", "method": "Independent standard-library Decimal(40) reconstruction; no import or execution of main replay",
        "decimal_precision": 40,
        "tolerances_absolute": {key: str(value) for key, value in TOLERANCES.items()},
        "limitations": [
            "Original archive authenticity is checked against the pinned manifest and adjacent CHECKSUM files; this checker does not independently download publisher files.",
            "H4 low-based stops identify an interval, not a demonstrated tick path. Noncanonical close liquidations are disclosed proxies.",
            "Exposure is the fraction of observed intervals occupied at their open or entered at that open, including intervals exited immediately at the open; it is not wall-clock invested duration.",
            "Synthetic execution cases inject completed-close indicator states to isolate chronology; separate indicator tests rebuild their own prices and reset states.",
        ],
    }
    checker = Comparison()
    try:
        report["checker_sha256"] = digest(Path(__file__))
        protocol_hash = digest(args.protocol)
        require(protocol_hash == FROZEN_SHA256, "Protocol differs from the final frozen SHA256")
        report["protocol_sha256"] = protocol_hash
        report["evidence_sha256"] = digest(args.evidence)
        protocol = read_json(args.protocol)
        evidence = read_json(args.evidence)
        require(int(protocol["timeframe_seconds"]) == STEP, "Unexpected timeframe")
        checker.compare(protocol, evidence["protocol"], "protocol")
        checker.compare(protocol_hash, evidence["protocol_sha256"], "protocol_sha256")
        report["synthetic_tests"] = [{"name": name, "status": "passed"}
                                     for name in run_synthetic_tests()]
        manifest = evidence["data_quality"]["sources"]
        require(len(manifest) == len({item["file"] for item in manifest}), "Duplicate archive manifest entry")
        if args.raw_dir is not None:
            raw, archives = load_original_rows(args.raw_dir, manifest, protocol)
            report["source_verification"] = {"mode": "all original ZIP rows", "archives": len(archives),
                                             "archive_rows": sum(item["rows"] for item in archives),
                                             "all_manifest_hashes_checksums_and_CRCs_passed": True}
        else:
            raw = [normalize_bar(bar) for bar in evidence["bars"]]
            report["source_verification"] = {"mode": "embedded raw prices only; original ZIP comparison not requested",
                                             "archives": 0, "archive_rows": 0}
        require(len(raw) == 14434, "Frozen study must contain all 14,434 source rows")
        require(raw[0]["ts"] == epoch(protocol["warmup_start"]), "Warmup start differs")
        last_close = max(epoch(window[1]) for window in protocol["periods"].values())
        require(raw[-1]["ts"] + STEP == last_close, "Final scheduled close differs")
        independent_quality = quality(raw, manifest)
        checker.compare(independent_quality, evidence["data_quality"], "data_quality")
        rows = rebuild_indicators(raw)
        checker.compare(rows, evidence["bars"], "bars")
        report["data_validation"] = {
            "all_rows_compared": len(rows), "first_open_utc": utc(rows[0]["ts"]),
            "last_scheduled_close_utc": utc(rows[-1]["ts"] + STEP),
            "missing_scheduled_intervals": independent_quality["missing_bars"],
            "noncanonical_source_closes": len(independent_quality["noncanonical_closes"]),
            "indicator_fields_rebuilt": ["wr_numerator", "wr_denominator", "wr", "ema200", "atr14", "eligible", "recovery_cross", "exit_level"],
        }
        runs = {}
        for variant, period in RUNS:
            key = variant + "_" + period
            runs[key] = account_path(rows, protocol, variant, period)
        checker.compare(runs, evidence["runs"], "runs")
        benchmarks = {period: buy_and_hold(rows, protocol, period) for period in protocol["periods"]}
        checker.compare(benchmarks, evidence["buy_hold"], "buy_hold")
        checker.compare(example_selection(rows, runs), evidence["examples"], "examples")
        report["replayed_accounts"] = {
            key: {"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((trade["pnl"] for trade in run["trades"]), ZERO)))}
            for key, run in runs.items()
        }
        report["additional_checks"] = {
            "restarted_buy_and_hold_paths": len(benchmarks), "protocol_selected_examples": len(evidence["examples"]),
            "annual_equity_returns_and_quality_exclusion_diagnostics": "compared",
            "all_trade_fields_and_close_equity_drawdown_points": "compared",
        }
        report["status"] = "passed" if checker.failures == 0 else "failed"
    except Exception as error:
        report["fatal_error"] = type(error).__name__ + ": " + str(error)
    report["comparison"] = {
        "numeric_values_compared": checker.numeric_count, "exact_values_compared": checker.exact_count,
        "failures": checker.failures, "failure_samples": checker.samples,
        "maximum_absolute_errors": {key: str(value) for key, value in checker.max_error.items()},
        "maximum_error_locations": checker.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({"status": report["status"], "report": str(args.report),
                      "comparison_failures": checker.failures,
                      "fatal_error": report.get("fatal_error"),
                      "synthetic_tests": len(report.get("synthetic_tests", []))}, indent=2))
    return 0 if report["status"] == "passed" else 1


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