#!/usr/bin/env python3
"""Independent Decimal(40) audit of the frozen BTCUSDT AO 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 btc-ao-independent-check.py --evidence btc-ao-evidence.json \
      --protocol btc-ao-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 BTC 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 = "4998e4f47b8e0a78b3a71d6fe1747fa6867f0bf3519c42b747bfaee6b9b10385"
TOLERANCES = {
    "account_USDT": D("0.000001"),
    "price_indicator_or_metric": D("0.00000001"),
    "quantity_BTC": 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_sma", "full"), ("no_sma", "early"), ("no_sma", "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_BTC" 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(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):
    """Bounded windows and a separately maintained ATR state; no replay calls."""
    medians = deque(maxlen=34)
    closes = deque(maxlen=200)
    initial_trs = []
    atr = None
    previous_close = None
    previous_ao = 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"]:
            medians.clear()
            closes.clear()
            initial_trs = []
            atr = None
            previous_close = None
            previous_ao = None
            count = 0
        bar.update(ao=None, sma200=None, atr14=None, eligible=False, up_cross=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
            medians.append((raw["high"] + raw["low"]) / D(2))
            closes.append(raw["close"])
            if atr is None:
                initial_trs.append(movement)
                if len(initial_trs) == 14:
                    atr = sum(initial_trs, ZERO) / D(14)
            else:
                atr += (movement - atr) / D(14)
            if len(medians) == 34:
                bar["ao"] = (sum(list(medians)[-5:], ZERO) / D(5)
                             - sum(medians, ZERO) / D(34))
            if len(closes) == 200:
                bar["sma200"] = sum(closes, ZERO) / D(200)
            bar["atr14"] = atr
            bar["eligible"] = count >= 200 and atr is not None and atr > ZERO
            bar["up_cross"] = (previous_ao is not None and bar["ao"] is not None
                               and previous_ao <= ZERO < bar["ao"])
            previous_close = raw["close"]
            previous_ao = bar["ao"]
        previous_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_sma" or bar["close"] > bar["sma200"]))


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_ao_exit=(reason == "ao_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, AO, 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_ao": queued_entry["ao"],
                    "signal_sma200": queued_entry["sma200"],
                    "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"], "ao_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 + STEP == finish:
                liquidate(bar, bar["close"], "period_end", "close")
            elif bar["ao"] is not None and bar["ao"] <= ZERO:
                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_ao_exits": sum(item["delayed_ao_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 = runs["primary_early"]["trades"][0]
    later = runs["primary_later"]["trades"][0]
    require(later["pnl"] != ZERO, "No opposite sign exists for a zero-P&L first later example")
    opposite = next(item for item in runs["primary_later"]["trades"]
                    if item["pnl"] * later["pnl"] < ZERO)
    result = []
    for label, trade in (("early", early), ("later", later), ("opposite", opposite)):
        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", ao="1",
            atr="5", eligible=False, crossed=False, canonical=True):
    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),
    })
    bar.update(ao=None if ao is None else D(ao), sma200=D("90"), atr14=D(atr),
               eligible=eligible, up_cross=crossed)
    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)

    # AO <= 0 is available at the first completed close; next open comes before
    # that next interval's low, even when the later low penetrates the fixed stop.
    bars = [signal, toy_bar(0, ao="-1"),
            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"] == "ao_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("queued_AO_exit_at_open_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, ao="-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 AO exit")
    results.append("stop_gap_has_priority_over_queued_AO_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_liquidates_with_entry_interval_counted_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_before_later_low")
    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, ao="-1"), toy_bar(2, opening="102", high="110", low="95")]
    trade = account_path(bars, toy_protocol(3), "primary", "toy")["trades"][0]
    require(trade["reason"] == "ao_exit" and trade["delayed_ao_exit"] and trade["crosses_gap"],
            "A queued AO exit did not survive a missing scheduled open")
    results.append("queued_AO_exit_survives_missing_open_and_is_flagged_delayed")

    # Entry opening remains usable although the close-time metadata is malformed.
    bars = [signal, toy_bar(0, low="85", close="100", ao=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_does_not_censor_available_open")

    bars = [signal, toy_bar(0, high="101", low="99", close="100", ao=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_explicitly_flagged_as_proxy")

    tiny_atr_signal = toy_bar(-1, atr="0.01", eligible=True, crossed=True)
    run = account_path([tiny_atr_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_entry_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", ao="-1"),
            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_funding_cap_includes_entry_fee_and_net_ledger_reconciles")

    # A malformed close ends an established segment; the next canonical bar has
    # no previous-close bridge, and both variants must wait for 200 new bars.
    raw = [toy_bar(slot, high="101", low="99", close="100") for slot in range(410)]
    raw[209]["source_close_raw"] -= 123
    raw = [normalize_bar(bar) for bar in raw]
    indicators = rebuild_indicators(raw)
    require(indicators[199]["eligible"] and indicators[208]["eligible"], "Initial 200-bar gate failed")
    require(not indicators[209]["canonical"] and all(indicators[209][field] is None
            for field in ("ao", "sma200", "atr14")), "Malformed close retained indicator values")
    require(not indicators[408]["eligible"] and indicators[409]["eligible"], "200-bar restart gate failed")
    require(indicators[222]["atr14"] is None and indicators[223]["atr14"] == D(2),
            "ATR did not seed from fourteen post-reset true ranges")
    require(indicators[242]["ao"] is None and indicators[243]["ao"] == ZERO,
            "AO did not require a new 34-bar median window")
    results.append("malformed_noncanonical_close_clears_all_indicators_and_restarts_14_34_200_gates")

    raw = [toy_bar(slot, high="1001", low="999", close="1000", opening="1000")
           for slot in range(200)]
    raw += [toy_bar(slot, high="101", low="99", 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(2)
            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_resets_without_cross_gap_TR_and_indicator_prefix_is_future_invariant")
    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("btc-ao-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": ["ao", "sma200", "atr14", "eligible", "up_cross"],
        }
        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": 3,
            "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())
