#!/usr/bin/env python3
"""Independent Decimal(40) audit of the frozen SOLUSDT ROC12 / EMA100 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 sol-roc-independent-check.py --evidence sol-roc-evidence.json \
      --protocol sol-roc-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.0000000001 SOL 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 = "1f66330c1db856453da9063313e4c430958d9ce77387f21c7230eabe9b8f40b0"
TOLERANCES = {
    "account_USDT": D("0.000001"),
    "price_indicator_or_metric": D("0.00000001"),
    "quantity_SOL": D("0.0000000001"),
}
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_SOL" 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 ("open", "high", "low", "close"):
        scaled = bar[key] * D(100000000)
        require(scaled == scaled.to_integral_value(), "Source price exceeds frozen eight-decimal scale")
        if key != "open":
            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):
    """Derive the rational12-bar change and Decimal EMA/ATR with bounded state."""
    close_window = deque(maxlen=13)
    ema_seed = []
    atr_seed = []
    ema = None
    atr = None
    alpha = D(2) / D(101)
    prior_close = None
    prior_numerator = None
    prior_timestamp = None
    segment_count = 0
    output = []
    for raw in rows:
        bar = dict(raw)
        gap = prior_timestamp is not None and raw["ts"] != prior_timestamp + STEP
        if gap or not raw["canonical"]:
            close_window.clear()
            ema_seed = []; atr_seed = []
            ema = None; atr = None
            prior_close = None; prior_numerator = None
            segment_count = 0
        bar.update(roc_numerator=None, roc_denominator=None, roc=None, ema100=None,
                   atr14=None, eligible=False, up_cross=False, exit_level=False)
        if raw["canonical"]:
            segment_count += 1
            movement = raw["high"] - raw["low"]
            if prior_close is not None:
                movement = max(movement, abs(raw["high"] - prior_close),
                               abs(raw["low"] - prior_close))
            if atr is None:
                atr_seed.append(movement)
                if len(atr_seed) == 14:
                    atr = sum(atr_seed, ZERO) / D(14)
            else:
                atr += (movement - atr) / D(14)
            if ema is None:
                ema_seed.append(raw["close"])
                if len(ema_seed) == 100:
                    ema = sum(ema_seed, ZERO) / D(100)
            else:
                ema += alpha * (raw["close"] - ema)
            close_window.append(raw["close_int"])
            numerator = None
            if len(close_window) == 13:
                denominator = close_window[0]
                require(denominator > 0, "ROC reference must be a positive source close")
                numerator = 100 * (raw["close_int"] - denominator)
                bar["roc_numerator"] = numerator
                bar["roc_denominator"] = denominator
                bar["roc"] = D(numerator) / D(denominator)
                bar["exit_level"] = numerator <= 0
                bar["up_cross"] = prior_numerator is not None and prior_numerator <= 0 < numerator
            bar["ema100"] = ema
            bar["atr14"] = atr
            bar["eligible"] = (segment_count >= 100 and atr is not None and atr > ZERO
                               and numerator is not None and prior_numerator is not None)
            prior_close = raw["close"]
            prior_numerator = numerator
        prior_timestamp = raw["ts"]
        output.append(bar)
    return output


def qualifies(bar, variant):
    return (bar is not None and bar["eligible"] and bar["up_cross"]
            and (variant == "no_ema" or bar["close"] > bar["ema100"]))


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_roc_exit=(reason == "roc_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, ROC 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_roc": queued_entry["roc"],
                    "signal_ema100": queued_entry["ema100"],
                    "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"], "roc_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_roc_exits": sum(item["delayed_roc_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:
            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", roc="5",
            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 roc is None else D(roc)
    denominator = 100000000 if value is not None else None
    numerator = int(value * denominator) if value is not None else None
    bar.update(roc_numerator=numerator, roc_denominator=denominator, roc=value,
               ema100=D(ema), atr14=D(atr), eligible=eligible,
               up_cross=crossed, exit_level=value is not None and value <= ZERO)
    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, roc="0"),
            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"] == "roc_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("ROC_level_exit_at_exact_zero_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, roc="-1"),
            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 ROC exit")
    results.append("stop_gap_has_priority_over_queued_ROC_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"]
            and trade["holding_intervals"] == 31,
            "Missed deadline failed to sell at first observed open before its low")
    results.append("missing_30th_interval_delays_to_first_observed_open_and_span_count_is31")
    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, roc="0"), toy_bar(2, opening="102", high="110", low="95", roc=None)]
    trade = account_path(bars, toy_protocol(3), "primary", "toy")["trades"][0]
    require(trade["reason"] == "roc_exit" and trade["delayed_roc_exit"] and trade["crosses_gap"],
            "Queued ROC exit failed to survive missing open and unavailable later reading")
    results.append("queued_ROC_exit_survives_missing_open_and_unavailable_later_value")

    bars = [signal, toy_bar(0, low="85", close="100", roc=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", roc=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 period close was not flagged as proxy")
    results.append("noncanonical_scheduled_period_close_is_flagged_proxy")

    for atr in ("0.01", "0.025", "51"):
        tiny_signal = toy_bar(-1, atr=atr, 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,
                "Nonpositive stop or stop at/above raw opening accepted")
    results.append("stop_must_be_positive_and_strictly_below_raw_open_including_equality")

    cap_signal = toy_bar(-1, atr="0.04", eligible=True, crossed=True)
    bars = [cap_signal, toy_bar(0, high="101", low="100", close="100", roc="0"),
            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 omitted entry fee")
    require(abs(run["metrics"]["end_cash"] - D(10000) - trade["pnl"]) < D("1e-25"),
            "Cash ledger and net realized P&L disagree")
    results.append("cash_cap_includes_entry_fee_and_net_cash_ledger_reconciles")

    raw = [toy_bar(slot, high="110", low="90", close="100") for slot in range(210)]
    raw[109]["source_close_raw"] -= 123
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[99]["eligible"] and rebuilt[108]["eligible"], "Initial100 gate failed")
    require(not rebuilt[109]["canonical"] and all(rebuilt[109][field] is None
            for field in ("roc", "ema100", "atr14", "roc_numerator", "roc_denominator")),
            "Noncanonical row retained indicators")
    require(not rebuilt[208]["eligible"] and rebuilt[209]["eligible"], "Restart100 gate failed")
    require(rebuilt[122]["atr14"] is None and rebuilt[123]["atr14"] == D(20),
            "ATR mean seed did not use14 new true ranges")
    require(rebuilt[121]["roc"] is None and rebuilt[122]["roc"] == ZERO,
            "ROC did not require13 new prices")
    results.append("noncanonical_close_restarts13_price_ROC14_TR_and100_gate")

    raw = [toy_bar(slot, high="1001", low="999", close="1000", opening="1000")
           for slot in range(100)]
    raw += [toy_bar(slot, high="110", low="90", close="100") for slot in range(101, 201)]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(not rebuilt[100]["eligible"] and rebuilt[113]["atr14"] == D(20)
            and rebuilt[-1]["eligible"], "Indicators bridged a missing H4 observation")
    prefix = rebuild_indicators([normalize_bar(bar) for bar in raw[:120]])
    require(prefix == rebuilt[:120], "Future prices changed earlier completed indicators")
    results.append("missing_bar_reset_first_TR_HminusL_and_prefix_future_invariance")

    raw = [toy_bar(slot, high="110", low="90", close="100") for slot in range(99)]
    raw.append(toy_bar(99, high="110", low="90", close="101"))
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[98]["roc"] == ZERO and not rebuilt[98]["eligible"]
            and rebuilt[99]["roc"] == ONE and rebuilt[99]["up_cross"]
            and rebuilt[99]["eligible"] and qualifies(rebuilt[99], "primary")
            and qualifies(rebuilt[99], "no_ema"), "Prior99/current100 equality entry failed")
    results.append("exact_previous_zero_equality_and_current100_prior99_gate")
    raw[-1] = toy_bar(99, high="110", low="90", close="100")
    equal = rebuild_indicators([normalize_bar(bar) for bar in raw])[-1]
    require(equal["roc"] == ZERO and equal["exit_level"] and not equal["up_cross"],
            "Current zero incorrectly entered or failed to exit")
    results.append("current_zero_is_exit_level_and_not_upward_entry")
    raw[-1] = toy_bar(99, high="400", low="90", close="400")
    high = rebuild_indicators([normalize_bar(bar) for bar in raw])[-1]
    require(high["roc"] == D(300) and high["up_cross"] and qualifies(high,"primary"),
            "Invented positive ROC ceiling blocked an otherwise valid entry")
    results.append("large_positive_ROC_cross_has_no_invented_upper_ceiling")

    raw = [toy_bar(slot, high="110", low="90", close="100") for slot in range(12)]
    raw.append(toy_bar(12, high="110", low="90", close="104"))
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(all(b["roc"] is None for b in rebuilt[:12]) and rebuilt[12]["roc"] == D(4)
            and not rebuilt[12]["up_cross"], "ROC12 used12 instead of13 prices or bridged missing priorROC")
    results.append("ROC12_requires13_prices_and_first_reading_has_no_cross")

    raw = [toy_bar(slot, opening="100", high="100", low="100", close="100")
           for slot in range(101)]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[12]["roc"] == ZERO and rebuilt[12]["roc_denominator"] > 0
            and rebuilt[99]["ema100"] == D(100) and rebuilt[99]["atr14"] == ZERO
            and not rebuilt[99]["eligible"], "Flat-price ROC was unavailable or zeroATR admitted")
    results.append("flat_prices_have_valid_zero_ROC_while_positive_ATR_gate_blocks_entry")

    raw = [toy_bar(slot, opening="110", high="120", low="90", close=str(100+slot))
           for slot in range(12)]
    raw += [toy_bar(12, opening="110", high="120", low="90", close="110"),
            toy_bar(13, opening="110", high="120", low="90", close="110")]
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[12]["close"] < rebuilt[11]["close"] and rebuilt[12]["roc"] == D(10)
            and rebuilt[13]["close"] == rebuilt[12]["close"]
            and rebuilt[13]["roc"] < rebuilt[12]["roc"], "Rolling reference semantics wrong")
    results.append("positive_ROC_can_accompany_down_last_candle_and_roll_down_on_flat_close")

    raw = [toy_bar(slot, opening="100", high="110", low="90", close="100") for slot in range(100)]
    raw.append(toy_bar(100, opening="100", high="120", low="90", close="110"))
    rebuilt = rebuild_indicators([normalize_bar(bar) for bar in raw])
    require(rebuilt[98]["ema100"] is None and rebuilt[99]["ema100"] == D(100)
            and abs(rebuilt[100]["ema100"] - (D(100) + D(20)/D(101))) < D("1e-35"),
            "EMA100 mean seed or2/101 recurrence failed")
    results.append("EMA100_mean_seed_then_alpha2over101_recursion")
    equal_ema = toy_bar(0, close="101", eligible=True, crossed=True, ema="101")
    require(not qualifies(equal_ema,"primary") and qualifies(equal_ema,"no_ema"),
            "Strict close>EMA filter or noEMAcontrol changed")
    results.append("strict_close_above_EMA_equality_blocked_but_control_removes_only_filter")

    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,
            "Missing terminal interval invented a final nominal close")
    results.append("period_end_uses_last_observed_close_and_actual_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("sol-roc-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) == 64 and len(manifest) == len({item["file"] for item in manifest}), "Archive manifest must contain64 unique files")
        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) == 11688, "Frozen study must contain all11,688 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": ["roc_numerator", "roc_denominator", "roc", "ema100", "atr14", "eligible", "up_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"]),
            "unavailable_example_tags": sorted({"early","later","opposite"} - {example["tag"] for example in 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())
