#!/usr/bin/env python3
"""Independent Decimal(50) verification of the frozen EURUSD RVI10 / EMA200 study.

The verifier reads the original seven HistData ZIP archives, recreates UTC H4
observations, indicators and accounts without importing the production replay.
Python's standard library and numpy are required. Numpy holds integer source
minutes; all indicator, execution, sizing and cash arithmetic uses Decimal.
"""
import argparse
import bisect
import calendar as cal
import datetime as dt
from decimal import Decimal, getcontext, ROUND_FLOOR, ROUND_CEILING
from fractions import Fraction
import hashlib
import io
import json
from pathlib import Path
import statistics
import sys
import zipfile
from zoneinfo import ZoneInfo

import numpy as np

getcontext().prec = 50
D = Decimal
ZERO = D(0)
ONE = D(1)
HUNDRED = D(100)
SCALE = 1000000
STEP = 14400
UTC = dt.timezone.utc
NY = ZoneInfo("America/New_York")
FROZEN = "c0f091960a6fbb6407a660984a90ad533d2fa51085d17877d297e031883c876f"
PINS = {
    "EURUSD-M1-2019.zip": "221fa4e0db549f48719273979ea4b1a2b0877f45f1147a8416ff8bbd055f5491",
    "EURUSD-M1-2020.zip": "38efbafce27f0e15df0006cc413cc02a68a18cada4f3b99e9afd42e17dd2ff2c",
    "EURUSD-M1-2021.zip": "64af4aa52958685a6889cfa15df400c62dc6ad543cf6ea10a13a0d3a7e01a563",
    "EURUSD-M1-2022.zip": "5ed361f3d93107f644834cac06870e830f9dc887d5aa5fde4b90c2accdf773f3",
    "EURUSD-M1-2023.zip": "26e41c4bccfd70f2c76ef7f3ffcba0e3b7097231927a41640f4a7c442815f34a",
    "EURUSD-M1-2024.zip": "58f074ba6b835eb2fbeaeb6678502a23b26768eefdfa509eb75ff5296bb2904d",
    "EURUSD-M1-2025.zip": "b7c23d20b9577588a8b13508d58fedbe487e569b7b8b5dd368bd1d2b61115de0",
}


def decimal(value):
    return value if isinstance(value, D) else D(str(value))


def require(ok, message):
    if not ok:
        raise AssertionError(message)


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


def iso(value):
    return dt.datetime.fromtimestamp(value, UTC).isoformat().replace("+00:00", "Z")


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


def price_integer(value):
    pieces = value.split(b".")
    whole = int(pieces[0])
    digits = pieces[1].rstrip(b"0") if len(pieces) == 2 else b""
    require(len(digits) <= 6, "Source precision is finer than 1e-6")
    return whole * SCALE + int((digits + b"000000")[:6])


def originals(folder, protocol):
    """Deduplicate byte-identical source lines before independent aggregation."""
    parts = []
    records = []
    duplicates = []
    backward = []
    raw_count = 0
    day_cache = {}
    first = epoch(protocol["warmup_start"])
    end = max(epoch(window[1]) for window in protocol["periods"].values())
    for name, expected_hash in sorted(PINS.items()):
        path = folder / name
        data = path.read_bytes()
        require(hashlib.sha256(data).hexdigest() == expected_hash, "Pinned ZIP changed: " + name)
        with zipfile.ZipFile(io.BytesIO(data)) as archive:
            require(archive.testzip() is None, "ZIP CRC failure: " + name)
            members = [n for n in archive.namelist() if n.lower().endswith(".csv")]
            require(len(members) == 1 and "EURUSD" in members[0], "Wrong source CSV identity")
            seen = {}
            lines = archive.read(members[0]).splitlines(keepends=True)
            raw_count += len(lines)
            rows = []
            previous_stamp = None
            for row_number, line in enumerate(lines, 1):
                columns = line.strip().split(b";")
                require(len(columns) == 6, "Expected six source columns")
                stamp = columns[0]
                if previous_stamp is not None and stamp < previous_stamp:
                    backward.append({"file": name, "row": row_number,
                                     "previous_stamp": previous_stamp.decode(), "stamp": stamp.decode()})
                previous_stamp = stamp
                if stamp in seen:
                    old_line, old_number = seen[stamp]
                    require(old_line == line, "Conflicting duplicate timestamp")
                    duplicates.append({"file": name, "first_row": old_number,
                                       "duplicate_row": row_number, "source_stamp": stamp.decode(),
                                       "line_sha256": hashlib.sha256(line).hexdigest()})
                    continue
                seen[stamp] = (line, row_number)
                require(len(stamp) == 15 and stamp[8:9] == b" ", "Invalid timestamp format")
                day = stamp[:8]
                if day not in day_cache:
                    day_cache[day] = cal.timegm((int(day[:4]), int(day[4:6]), int(day[6:8]), 0, 0, 0))
                timestamp = (day_cache[day] + int(stamp[9:11])*3600
                             + int(stamp[11:13])*60 + int(stamp[13:15]) + 18000)
                require(timestamp % 60 == 0, "Source timestamp is not a minute")
                o, h, l, c = [price_integer(x) for x in columns[1:5]]
                require(0 < l <= min(o, c) <= max(o, c) <= h, "Invalid source OHLC")
                if first <= timestamp < end:
                    rows.append((timestamp, o, h, l, c))
            parts.append(np.asarray(rows, dtype=np.int64))
            records.append({"file": name, "sha256": expected_hash, "bytes": len(data),
                            "csv": members[0], "source_rows": len(lines)})
    minutes = np.concatenate(parts)
    minutes = minutes[np.argsort(minutes[:, 0], kind="stable")]
    require(bool(np.all(np.diff(minutes[:, 0]) > 0)), "Retained UTC minutes not unique and ascending")
    return minutes, {"source_files": len(records), "rows": len(minutes),
                     "raw_rows_all_archives": raw_count,
                     "exact_duplicate_rows_removed": len(duplicates),
                     "duplicate_audit": duplicates, "source_backward_jumps": backward,
                     "sources": records, "first_ts": int(minutes[0,0]), "last_ts": int(minutes[-1,0])}


def h4_observations(minutes):
    result = []
    current = None
    for source in minutes:
        timestamp = int(source[0])
        anchor = timestamp - timestamp % STEP
        if current is None or anchor != current["ts"]:
            if current is not None:
                result.append(current)
            current = {"ts": anchor, "source_open_int": int(source[1]),
                       "source_high_int": int(source[2]), "source_low_int": int(source[3]),
                       "source_close_int": int(source[4]), "n": 1,
                       "first_ts": timestamp, "last_ts": timestamp}
        else:
            current["source_high_int"] = max(current["source_high_int"], int(source[2]))
            current["source_low_int"] = min(current["source_low_int"], int(source[3]))
            current["source_close_int"] = int(source[4])
            current["n"] += 1
            current["last_ts"] = timestamp
    if current is not None:
        result.append(current)
    for row in result:
        for field in ("open", "high", "low", "close"):
            row[field] = D(row["source_"+field+"_int"]) / SCALE
    return result


def ema_stream(values, length):
    seed = []
    average = None
    alpha = D(2) / (length+1)
    result = []
    for value in values:
        if value is None:
            result.append(None)
            continue
        if average is None:
            seed.append(value)
            if len(seed) == length:
                average = sum(seed, ZERO) / length
        else:
            average = alpha*value + (ONE-alpha)*average
        result.append(average)
    return result


def indicators(rows):
    """Rebuild the two weighted component streams before dividing ten sums."""
    price_ema = ema_stream([row["close"] for row in rows], 200)
    bodies = [row["source_close_int"]-row["source_open_int"] for row in rows]
    ranges = [row["source_high_int"]-row["source_low_int"] for row in rows]
    kernel_bodies, kernel_ranges = [], []
    for index in range(len(rows)):
        if index < 3:
            kernel_bodies.append(None)
            kernel_ranges.append(None)
        else:
            kernel_bodies.append(sum(weight*bodies[index-lag] for lag,weight in enumerate((1,2,2,1))))
            kernel_ranges.append(sum(weight*ranges[index-lag] for lag,weight in enumerate((1,2,2,1))))
    main = []
    for index in range(len(rows)):
        denominator = sum(kernel_ranges[index-9:index+1]) if index >= 12 else None
        numerator = sum(kernel_bodies[index-9:index+1]) if index >= 12 else None
        main.append(Fraction(numerator,denominator) if denominator else None)
    signal = []
    for index in range(len(rows)):
        values = main[index-3:index+1] if index >= 15 else []
        signal.append(sum((weight*value for weight,value in zip((1,2,2,1),values)),Fraction(0))/6
                      if len(values)==4 and all(value is not None for value in values) else None)
    true_ranges = []
    atr = None
    for index,row in enumerate(rows):
        true_range = row["high"]-row["low"]
        if index:
            previous_close = rows[index-1]["close"]
            true_range = max(true_range,abs(row["high"]-previous_close),abs(row["low"]-previous_close))
        true_ranges.append(true_range)
        if index==13:
            atr=sum(true_ranges,ZERO)/14
        elif index>13:
            atr=(D(13)*atr+true_range)/14
        rvi,average=main[index],signal[index]
        row.update(kernel_body_int=kernel_bodies[index],kernel_range_int=kernel_ranges[index],
                   body_sum_int=sum(kernel_bodies[index-9:index+1]) if index>=12 else None,
                   range_sum_int=sum(kernel_ranges[index-9:index+1]) if index>=12 else None,
                   rvi=rvi,signal=average,rvi_exact=None if rvi is None else str(rvi),
                   signal_exact=None if average is None else str(average),
                   ema200=price_ema[index],atr14=atr)
        ema=row["ema200"]
        row["ema_side"]=0 if ema is None or row["close"]==ema else (1 if row["close"]>ema else -1)
        row["raw_cross"]=crossing(rows,index)
        row["cross"]=entry_cross(rows,index)
        row["exit_long"]=rvi is not None and average is not None and rvi<=average
        row["exit_short"]=rvi is not None and average is not None and rvi>=average
    return rows


def crossing(rows,index):
    if index==0:
        return 0
    previous,current=rows[index-1],rows[index]
    if current["ts"]-previous["ts"]!=STEP:
        return 0
    values=[previous.get("rvi"),previous.get("signal"),current.get("rvi"),current.get("signal")]
    if any(value is None for value in values):
        return 0
    a,b,x,y=values
    return 1 if a<=b and x>y else -1 if a>=b and x<y else 0


def entry_cross(rows,index):
    row=rows[index]
    if index<199 or row.get("ema200") is None or row.get("atr14") is None or row["atr14"]<=0:
        return 0
    return crossing(rows,index)


def calendar_events(start, end):
    rollovers, sessions, fridays = [], [], []
    day = dt.datetime.fromtimestamp(start, UTC).astimezone(NY).date()-dt.timedelta(days=8)
    last = dt.datetime.fromtimestamp(end, UTC).astimezone(NY).date()+dt.timedelta(days=8)
    while day <= last:
        at = int(dt.datetime.combine(day, dt.time(17), NY).timestamp())
        if day.weekday() < 5:
            rollovers.append((at, 3 if day.weekday() == 2 else 1))
        if day.weekday() == 4:
            fridays.append(at)
        if day.weekday() == 6:
            finish = int(dt.datetime.combine(day+dt.timedelta(days=5), dt.time(17), NY).timestamp())
            sessions.append((at, finish))
        day += dt.timedelta(days=1)
    return rollovers, sessions, fridays


def gap_quality(minutes, sessions):
    gaps = []
    unobserved = []
    starts = [s[0] for s in sessions]
    outside = 0
    for i in np.flatnonzero(np.diff(minutes[:,0]) > 60):
        left, right = int(minutes[i,0]), int(minutes[i+1,0])
        count = (right-left)//60-1
        inside = 0
        k = max(0, bisect.bisect_right(starts, left+60)-1)
        while k < len(sessions) and sessions[k][0] < right:
            begin = max(left+60, sessions[k][0])
            finish = min(right, sessions[k][1])
            if finish > begin:
                inside += (finish-begin)//60
                unobserved.extend(range(begin, finish, 60))
            k += 1
        outside += count-inside
        gaps.append({"left":left, "right":right, "missing_minutes":count,
                     "in_session_unobserved":inside, "outside_weekly_session":count-inside})
    return sorted(unobserved), {"gaps":gaps, "gap_count":len(gaps),
                                "missing_minutes":len(unobserved)+outside,
                                "in_session_unobserved_minutes":len(unobserved),
                                "outside_weekly_session_minutes":outside}


def cost_values(protocol, variant):
    scenario = variant if variant in ("zero_cost", "higher_cost") else "baseline"
    raw = protocol["costs"][scenario]
    pip = decimal(protocol["pip_size"])
    return {"scenario":scenario, "spread":decimal(raw["spread_pips"])*pip,
            "slip":decimal(raw["slippage_pips_per_leg"])*pip,
            "commission":decimal(raw["commission_usd_per_100000_eur_per_leg"])/100000,
            "carry":decimal(raw["carry_pips_per_rollover_unit"])*pip}


def rollover_units(rollovers, entry, event, kind):
    return sum(units for cutoff, units in rollovers if entry < cutoff
               and (cutoff <= event if kind == "within_1m" else cutoff < event))


def inside_session(timestamp, sessions):
    starts = [s[0] for s in sessions]
    index = bisect.bisect_right(starts, timestamp)-1
    return index >= 0 and sessions[index][0] <= timestamp < sessions[index][1]


def entry_gate(direction, close, ema, variant):
    return variant=="no_ema" or (close>ema if direction==1 else close<ema)


def already_flat(last, decision):
    return last is None or decision>last["exit_event_ts"] or (decision==last["exit_event_ts"] and last["exit_event_kind"]=="close")


def first_exit(minutes, entry_index, bars, direction, stop, costs, entry, deadline, deadline_reason, end):
    """Walk observed minute phases and release only already-completed H4 states."""
    cutoffs = [row["ts"]+STEP for row in bars]
    next_close = bisect.bisect_right(cutoffs, entry)
    pending = None
    # Integer threshold comparisons are exactly equivalent to Decimal quotes.
    stop_bid = stop-(costs["spread"] if direction == -1 else ZERO)
    threshold = int((stop_bid*SCALE).to_integral_value(
        rounding=ROUND_FLOOR if direction == 1 else ROUND_CEILING))
    last_index = None
    for index in range(entry_index, len(minutes)):
        minute = minutes[index]
        timestamp = int(minute[0])
        if timestamp >= end:
            break
        while next_close < len(bars) and cutoffs[next_close] <= timestamp:
            row = bars[next_close]
            if row["rvi"] is not None and row["signal"] is not None:
                exit_level = row["rvi"] <= row["signal"] if direction == 1 else row["rvi"] >= row["signal"]
                if exit_level and pending is None:
                    pending = cutoffs[next_close]
            next_close += 1
        opening = int(minute[1])
        crossed_open = opening <= threshold if direction == 1 else opening >= threshold
        ref_open = D(opening)/SCALE+(costs["spread"] if direction == -1 else ZERO)
        if crossed_open:
            return {"index":index, "event_ts":timestamp, "kind":"open", "ref":ref_open,
                    "reason":"stop_gap", "queue_ts":pending, "terminal_fallback":False}
        if pending is not None and timestamp >= pending:
            return {"index":index, "event_ts":timestamp, "kind":"open", "ref":ref_open,
                    "reason":"signal_exit", "queue_ts":pending, "terminal_fallback":False}
        if timestamp >= deadline:
            return {"index":index, "event_ts":timestamp, "kind":"open", "ref":ref_open,
                    "reason":deadline_reason, "queue_ts":pending, "terminal_fallback":False}
        extremum = int(minute[3] if direction == 1 else minute[2])
        crossed_range = extremum <= threshold if direction == 1 else extremum >= threshold
        if crossed_range:
            return {"index":index, "event_ts":timestamp, "kind":"within_1m", "ref":stop,
                    "reason":"stop", "queue_ts":pending, "terminal_fallback":False}
        last_index = index
        if timestamp+60 == deadline:
            ref = D(int(minute[4]))/SCALE+(costs["spread"] if direction == -1 else ZERO)
            return {"index":index, "event_ts":deadline, "kind":"close", "ref":ref,
                    "reason":deadline_reason, "queue_ts":pending, "terminal_fallback":False}
    require(last_index is not None, "No in-period quote after entry")
    minute = minutes[last_index]
    ref = D(int(minute[4]))/SCALE+(costs["spread"] if direction == -1 else ZERO)
    return {"index":last_index, "event_ts":int(minute[0])+60, "kind":"close", "ref":ref,
            "reason":"period_end", "queue_ts":pending, "terminal_fallback":True}


def replay(rows, minutes, protocol, variant, period, rollovers, sessions, fridays, missing):
    begin, end = [epoch(value) for value in protocol["periods"][period]]
    costs = cost_values(protocol, variant)
    cash = decimal(protocol["account"]["initial_cash"])
    trades = []
    canceled = rejected = outside = capped = 0
    minute_times = minutes[:,0]
    by_anchor = {r["ts"]:r for r in rows}
    last = None
    for i, row in enumerate(rows):
        decision = row["ts"]+STEP
        if not begin <= decision < end:
            continue
        direction = entry_cross(rows, i)
        if not direction:
            continue
        if not entry_gate(direction,row["close"],row["ema200"],variant):
            continue
        if not already_flat(last,decision):
            continue
        if not inside_session(decision, sessions):
            outside += 1
            continue
        entry_index = int(np.searchsorted(minute_times, decision))
        if entry_index == len(minutes) or int(minutes[entry_index,0]) != decision:
            canceled += 1
            continue
        bid = D(int(minutes[entry_index,1]))/SCALE
        entry_fill = bid+(costs["spread"] if direction == 1 else ZERO)+direction*costs["slip"]
        stop = entry_fill-direction*D(2)*row["atr14"]
        live_quote = bid+(costs["spread"] if direction == -1 else ZERO)
        if stop <= 0 or not (stop < live_quote if direction == 1 else stop > live_quote):
            rejected += 1
            continue
        unit = D(2)*row["atr14"]+costs["slip"]+D(2)*costs["commission"]
        risk_quantity = decimal(protocol["account"]["risk_fraction"])*cash/unit
        cap_quantity = cash/(abs(entry_fill)+costs["commission"])
        quantity = min(risk_quantity, cap_quantity)
        is_capped = cap_quantity < risk_quantity
        capped += is_capped
        friday = fridays[bisect.bisect_right(fridays, decision)]
        deadline, _, deadline_reason = min((decision+30*STEP,0,"time"), (friday,1,"week_close"), (end,2,"period_end"))
        event = first_exit(minutes, entry_index, rows, direction, stop, costs, decision,
                           deadline, deadline_reason, end)
        timestamp, kind = event["event_ts"], event["kind"]
        fill = event["ref"]-direction*costs["slip"]
        units = rollover_units(rollovers, decision, timestamp, kind)
        fees = D(2)*quantity*costs["commission"]
        financing = quantity*costs["carry"]*units
        # Group the exact per-EUR cost identity before multiplying quantity.
        # Separate rounded cash products can turn a mathematically flat trade
        # into a tiny signed residual, incorrectly changing the win count.
        unit_pnl = direction*(fill-entry_fill)-D(2)*costs["commission"]-costs["carry"]*units
        pnl = quantity*unit_pnl
        lo = bisect.bisect_right(missing, decision)
        hi = bisect.bisect_right(missing, timestamp) if kind == "within_1m" else bisect.bisect_left(missing, timestamp)
        source_minute = int(minutes[event["index"],0])
        exit_anchor = source_minute-source_minute%STEP
        exit_row = by_anchor[exit_anchor]
        future_level = next((r["ts"]+STEP for r in rows if r["ts"]+STEP>decision
                              and r["rvi"] is not None and r["signal"] is not None
                              and (r["rvi"] <= r["signal"] if direction==1 else r["rvi"] >= r["signal"])),None)
        trade = {"number":len(trades)+1, "variant":variant, "period":period,
                 "side":"long" if direction == 1 else "short", "direction":direction,
                 "signal_ts":row["ts"], "signal_bar_ts":row["ts"], "decision_ts":decision,
                 "entry_ts":decision, "exit_event_ts":timestamp, "exit_event_kind":kind,
                 "exit_event_precision":{"open":"at_open","close":"at_close","within_1m":"within_1m"}[kind],
                 "exit_bar_ts":exit_anchor, "source_exit_minute_ts":source_minute,
                 "entry":entry_fill, "entry_ref":bid, "exit":fill,
                 "exit_ref":event["ref"], "exit_bid_ref":event["ref"]-(costs["spread"] if direction == -1 else ZERO),
                 "stop":stop, "signal_atr":row["atr14"], "signal_rvi":row["rvi"], "signal":row["signal"], "signal_ema200":row["ema200"],
                 "quantity":quantity, "qty":quantity, "preentry_equity":cash,
                 "risk_cash":quantity*unit, "lunit":unit, "notional":quantity*abs(entry_fill),
                 "notional_capped":is_capped, "pnl":pnl, "net_r":pnl/(quantity*unit),
                 "fees":fees, "financing":financing, "rollover_units":units,
                 "spread_cost":quantity*costs["spread"], "slippage_cost":D(2)*quantity*costs["slip"],
                 "cash_after":cash+pnl, "reason":event["reason"], "deadline":deadline,
                 "deadline_reason":deadline_reason, "terminal_fallback":event["terminal_fallback"],
                 "crosses_gap":hi>lo, "missing_open_minutes_crossed":hi-lo,
                 "partial_signal":row["n"] < 240, "partial_exit_bucket":exit_row["n"] < 240,
                 "stale_signal_close":row["last_ts"]+60 != row["ts"]+STEP,
                 "queued_exit_ts":future_level,
                 "delayed_signal_exit":event["reason"]=="signal_exit" and future_level is not None and timestamp>future_level,
                 "quote_side_exit":"Bid" if direction==1 else "modeled Ask",
                 "holding_bars":D(timestamp-decision)/STEP,
                 "holding_h4_slots_lower":D(timestamp-decision)/STEP,
                 "holding_h4_slots_upper":D(timestamp-decision+(60 if kind == "within_1m" else 0))/STEP}
        trades.append(trade)
        cash += pnl
        last = trade
    equity = []
    settled = decimal(protocol["account"]["initial_cash"])
    peak = settled
    position = 0
    occupied_count = 0
    for row in rows:
        if not begin <= row["ts"] < end:
            continue
        cutoff = min(row["ts"]+STEP, end)
        while position < len(trades):
            trade = trades[position]
            done = trade["exit_event_ts"] < cutoff or (trade["exit_event_ts"] == cutoff and trade["exit_event_kind"] == "close")
            if not done:
                break
            settled = trade["cash_after"]
            position += 1
        value = settled
        if position < len(trades) and trades[position]["entry_ts"] < cutoff:
            trade = trades[position]
            kind = trade["exit_event_kind"] if trade["exit_event_ts"] == cutoff else "within_1m"
            units = rollover_units(rollovers, trade["entry_ts"], cutoff, kind)
            liquidation = row["close"]+(costs["spread"] if trade["direction"] == -1 else ZERO)-trade["direction"]*costs["slip"]
            value = trade["preentry_equity"]+trade["direction"]*trade["quantity"]*(liquidation-trade["entry"])-D(2)*trade["quantity"]*costs["commission"]-trade["quantity"]*costs["carry"]*units
        occupied = any(trade["entry_ts"] < cutoff and (trade["exit_event_ts"] > row["ts"]
                       or (trade["exit_event_ts"] == row["ts"] and trade["exit_event_kind"] == "within_1m")) for trade in trades)
        occupied_count += occupied
        peak = max(peak, value)
        equity.append({"ts":cutoff, "bar_ts":row["ts"], "equity":value,
                       "drawdown_pct":HUNDRED*(peak-value)/peak, "cash":settled, "occupied":occupied})
    profits = [t["pnl"] for t in trades]
    ratios = [t["net_r"] for t in trades]
    gain = sum((p for p in profits if p > 0), ZERO)
    loss = -sum((p for p in profits if p < 0), ZERO)
    cumulative = maximum_r = drawdown_r = ZERO
    for ratio in ratios:
        cumulative += ratio
        maximum_r = max(maximum_r, cumulative)
        drawdown_r = max(drawdown_r, maximum_r-cumulative)
    metrics = {"return_pct":HUNDRED*(cash/decimal(protocol["account"]["initial_cash"])-ONE),
               "end_cash":cash, "trades":len(trades), "wins":sum(p>0 for p in profits),
               "losses":sum(p<0 for p in profits), "breakevens":sum(p==0 for p in profits),
               "profit_factor":gain/loss if loss else None,
               "mean_r":sum(ratios,ZERO)/len(ratios) if ratios else None,
               "median_r":statistics.median(ratios) if ratios else None,
               "sum_r":sum(ratios,ZERO), "drawdown_r":drawdown_r,
               "drawdown_pct":max((p["drawdown_pct"] for p in equity), default=ZERO),
               "fees":sum((t["fees"] for t in trades),ZERO),
               "financing":sum((t["financing"] for t in trades),ZERO),
               "rollover_units":sum(t["rollover_units"] for t in trades),
               "exposure_pct":HUNDRED*occupied_count/len(equity) if equity else ZERO,
               "spread_cost":sum((t["spread_cost"] for t in trades),ZERO),
               "slippage_cost":sum((t["slippage_cost"] for t in trades),ZERO),
               "notional_capped":capped, "cash_capped":capped,
               "canceled_missing_entry":canceled, "invalid_stop_entries":rejected,
               "outside_weekly_session_entries":outside, "gap_trades":sum(t["crosses_gap"] for t in trades),
               "partial_signal_trades":sum(t["partial_signal"] for t in trades),
               "stale_signal_trades":sum(t["stale_signal_close"] for t in trades),
               "partial_exit_trades":sum(t["partial_exit_bucket"] for t in trades),
               "delayed_signal_exits":sum(t["delayed_signal_exit"] for t in trades),
               "terminal_fallbacks":sum(t["terminal_fallback"] for t in trades),
               "long_trades":sum(t["direction"]==1 for t in trades),
               "short_trades":sum(t["direction"]==-1 for t in trades),
               "mean_holding":sum((t["holding_bars"] for t in trades),ZERO)/len(trades) if trades else None,
               "median_holding":statistics.median(t["holding_bars"] for t in trades) if trades else None}
    annual = []
    groups = {}
    start_cash = decimal(protocol["account"]["initial_cash"])
    for point in equity:
        year = dt.datetime.fromtimestamp(point["bar_ts"],UTC).year
        groups[year] = point["equity"]
    for year, finish in sorted(groups.items()):
        annual.append({"year":year, "return_pct":HUNDRED*(finish/start_cash-ONE),
                       "start_equity":start_cash, "end_equity":finish})
        start_cash = finish
    return {"variant":variant, "period":period, "start_ts":begin,"end_ts":end,"metrics":metrics,
            "trades":trades, "equity":equity, "annual":annual}


class Compare:
    def __init__(self):
        self.numeric = 0
        self.exact = 0
        self.failures = 0
        self.samples = []
        self.max_errors = {}
        self.max_locations = {}
        self.fields = set()

    def failure(self, path, expected, actual, tolerance=None):
        self.failures += 1
        if len(self.samples) < 30:
            self.samples.append({"path":path, "expected":str(expected), "actual":str(actual),
                                 "tolerance":str(tolerance) if tolerance is not None else None})

    def one(self, expected, actual, path):
        self.fields.add(path.split(".")[-1])
        if isinstance(expected,bool) or expected is None or isinstance(expected,str) or isinstance(expected,int):
            self.exact += 1
            if expected != actual or (isinstance(expected,bool) and not isinstance(actual,bool)):
                self.failure(path,expected,actual)
            return
        if isinstance(expected,Fraction):
            expected=D(expected.numerator)/D(expected.denominator)
        if isinstance(expected,(D,float)):
            self.numeric += 1
            key = path.split(".")[-1]
            kind = "money" if key in {"equity","cash","end_cash","cash_after","preentry_equity","risk_cash","pnl","fees","financing","notional","spread_cost","slippage_cost","start_equity","end_equity","retained_ledger_pnl"} else "quantity" if key in {"qty","quantity"} else "price_or_metric"
            tolerance = D("0.000001") if kind == "money" else D("0.0000001") if kind == "quantity" else D("0.00000001")
            if actual is None:
                self.failure(path,expected,actual,tolerance)
                return
            error = abs(decimal(expected)-decimal(actual))
            if error > self.max_errors.get(kind,ZERO):
                self.max_errors[kind] = error
                self.max_locations[kind] = path
            if error > tolerance:
                self.failure(path,expected,actual,tolerance)
            return
        raise TypeError(type(expected).__name__)

    def matching(self, expected, actual, path, require_all=True):
        if isinstance(expected,dict):
            require(isinstance(actual,dict),path+" must be an object")
            for key,value in expected.items():
                if key in actual:
                    self.matching(value,actual[key],path+"."+key,require_all)
                elif require_all:
                    self.failure(path+"."+key,value,"MISSING")
        elif isinstance(expected,list):
            require(isinstance(actual,list),path+" must be a list")
            self.one(len(expected),len(actual),path+".length")
            for index,(a,b) in enumerate(zip(expected,actual)):
                self.matching(a,b,path+"."+str(index),require_all)
        else:
            self.one(expected,actual,path)


def toy_rows(count=65):
    return [{"ts":i*STEP,"open":D(1),"high":D("1.01"),"low":D("0.99"),
             "close":D(1),"n":240,"first_ts":i*STEP,"last_ts":i*STEP+STEP-60,
             "source_open_int":SCALE,"source_high_int":1010000,"source_low_int":990000,
             "source_close_int":SCALE} for i in range(count)]


def synthetic_tests():
    tests=[]
    def check(name, condition):
        require(condition,"Synthetic failure: "+name)
        tests.append({"name":name,"status":"passed"})
    rows=indicators(toy_rows(220))
    check("kernel/RVI/signal/EMA seeds at3/12/15/199",all(next(i for i,r in enumerate(rows) if r[k] is not None)==v for k,v in (("kernel_body_int",3),("rvi",12),("signal",15),("ema200",199))))
    check("constant bodies produce exact zero and no crossing",all(r["cross"]==0 for r in rows) and all(r["rvi"]==0 for r in rows[12:]))
    check("common200 gate unavailable until index199",all(r["cross"]==0 for r in rows[:199]))
    changing=toy_rows(30)
    for i,r in enumerate(changing):
        r["source_close_int"]+=i*100
        r["close"]=D(r["source_close_int"])/SCALE
    measured=indicators(changing)
    check("weighted kernel current-to-oldest1-2-2-1",measured[3]["kernel_body_int"]==900)
    U=sum(sum(w*(changing[j-k]["source_close_int"]-changing[j-k]["source_open_int"]) for k,w in enumerate((1,2,2,1))) for j in range(3,13))
    R=sum(sum(w*(changing[j-k]["source_high_int"]-changing[j-k]["source_low_int"]) for k,w in enumerate((1,2,2,1))) for j in range(3,13))
    check("RVI is ratio of ten weighted sums",measured[12]["rvi"]==Fraction(U,R))
    check("signal smooths RVI with1-2-2-1",measured[15]["signal"]==(measured[15]["rvi"]+2*measured[14]["rvi"]+2*measured[13]["rvi"]+measured[12]["rvi"])/6)
    check("ratio of sums differs from mean of ratios",Fraction(1-1,1+9)==0 and (Fraction(1,1)+Fraction(-1,9))/2==Fraction(4,9))
    pair=toy_rows(2)
    pair[0].update(rvi=Fraction(0),signal=Fraction(0),atr14=D(".01"))
    pair[1].update(rvi=Fraction(1),signal=Fraction(0),atr14=D(".01"))
    check("previous equality qualifies bullish crossing",crossing(pair,1)==1)
    pair[1]["rvi"]=Fraction(0)
    check("current equality does not cross",crossing(pair,1)==0)
    pair[1].update(rvi=Fraction(-1),signal=Fraction(0))
    check("previous equality qualifies bearish crossing",crossing(pair,1)==-1)
    pair[1]["ts"]+=STEP
    check("scheduled gap blocks crossing",crossing(pair,1)==0)
    for direction in (1,-1):
        check("price equality fails primary direction"+str(direction),not entry_gate(direction,D(1),D(1),"primary"))
        check("control removes only price gate direction"+str(direction),entry_gate(direction,D(1),D(1),"no_ema"))
    check("primary long aboveEMA",entry_gate(1,D("1.01"),D(1),"primary"))
    check("primary short belowEMA",entry_gate(-1,D(".99"),D(1),"primary"))
    check("EMA gate does not require positiveRVI",entry_gate(1,D("1.01"),D(1),"primary") and Fraction(-1,2)<0)
    gapped=toy_rows(220)
    for r in gapped[40:]:r["ts"]+=2*STEP
    rebuilt=indicators(gapped)
    check("indicator observations continue across scheduled gaps",rebuilt[199]["ema200"]==D(1) and rebuilt[40]["rvi"]==Fraction(0))
    flat=toy_rows(40)
    for r in flat:r.update(high=D(1),low=D(1),source_high_int=SCALE,source_low_int=SCALE)
    flat=indicators(flat)
    check("zero denominator is unavailable rather than zero",all(r["rvi"] is None and r["signal"] is None for r in flat))
    oneflat=toy_rows(20);oneflat[10].update(high=D(1),low=D(1),source_high_int=SCALE,source_low_int=SCALE)
    check("individual flat candle does not force undefined ratio",indicators(oneflat)[15]["rvi"]==0)
    recovery=toy_rows(50)
    for r in recovery[10:35]:r.update(high=D(1),low=D(1),source_high_int=SCALE,source_low_int=SCALE)
    recovery=indicators(recovery)
    index=next(i for i,r in enumerate(recovery[35:],35)if r["rvi"] is not None)
    check("signal never skips undefined main readings",all(recovery[i]["signal"] is None for i in range(index,index+3)) and recovery[index+3]["signal"] is not None)
    check("line equality exits without entrywarmup",rows[15]["exit_long"] and rows[15]["exit_short"] and rows[15]["cross"]==0)
    jump=toy_rows(14)
    jump[-1].update(ts=20*STEP,close=D(2),high=D("2.01"),low=D("1.99"),source_close_int=2000000,source_high_int=2010000,source_low_int=1990000)
    indicators(jump)
    check("ATR retains previous observed close across gap",jump[-1]["atr14"]==(D(13)*D(".02")+D("1.01"))/14)
    start=epoch("2024-01-01T00:00:00Z");end=epoch("2025-01-01T00:00:00Z")
    roll,sessions,fridays=calendar_events(start,end)
    check("winter Friday close UTC22",epoch("2024-01-05T22:00:00Z") in fridays)
    check("summer Friday close UTC21",epoch("2024-07-05T21:00:00Z") in fridays)
    w=epoch("2024-01-03T22:00:00Z")
    check("Wednesday triple debit",rollover_units(roll,w-1,w,"within_1m")==3)
    check("entry at rollover excludes preceding unit",rollover_units(roll,w,w+1,"within_1m")==0)
    check("exact opening exit excludes rollover",rollover_units(roll,w-1,w,"open")==0)
    check("exact close exit excludes rollover",rollover_units(roll,w-1,w,"close")==0)
    check("Friday close is excluded from entry session",not inside_session(epoch("2024-07-05T21:00:00Z"),sessions))
    check("Sunday opening is included in entry session",inside_session(epoch("2024-07-07T21:00:00Z"),sessions))
    check("same opening exit forbids reentry",not already_flat({"exit_event_ts":100,"exit_event_kind":"open"},100))
    check("same minute intrabar exit forbids reentry",not already_flat({"exit_event_ts":100,"exit_event_kind":"within_1m"},100))
    check("completed preceding minute exit permits fresh decision",already_flat({"exit_event_ts":100,"exit_event_kind":"close"},100))
    base={"spread":D(".0001"),"slip":D(".00001"),"commission":D(".000035"),"carry":D(".00002")}
    b=[{"ts":0,"rvi":D(1),"signal":D(0)},{"ts":STEP,"rvi":D(-1),"signal":D(0)}]
    minute=np.array([[0,1000000,1001000,999500,1000000],[STEP,998000,1001000,997000,998000]],dtype=np.int64)
    x=first_exit(minute,0,b,1,D(".999"),base,0,10*STEP,"time",20*STEP)
    check("opening stop gap has priority",x["reason"]=="stop_gap" and x["ref"]==D(".998"))
    # An exit level becomes available at2STEP; the queued opening precedes its later low.
    minute=np.array([[0,1000000,1001000,999500,1000000],[2*STEP,1000000,1001000,998000,1000000]],dtype=np.int64)
    x=first_exit(minute,0,b,1,D(".999"),base,0,10*STEP,"time",20*STEP)
    check("queued indicator exit precedes later minute low",x["reason"]=="signal_exit" and x["event_ts"]==2*STEP and x["kind"]=="open")
    minute[1,0]+=60
    x=first_exit(minute,0,b,1,D(".999"),base,0,10*STEP,"time",20*STEP)
    check("missing scheduled exit opening keeps queue",x["reason"]=="signal_exit" and x["queue_ts"]==2*STEP and x["event_ts"]==2*STEP+60)
    minute[1,0]=4*STEP
    x=first_exit(minute,0,b,1,D(".999"),base,0,3*STEP,"time",20*STEP)
    check("pending indicator beats overdue deadline after gap",x["reason"]=="signal_exit" and x["event_ts"]==4*STEP)
    minute[1,1]=998000
    x=first_exit(minute,0,b,1,D(".999"),base,0,3*STEP,"time",20*STEP)
    check("opening stop gap beats both queued and overdue exits",x["reason"]=="stop_gap")
    minute=np.array([[0,1000000,1000200,999900,1000000]],dtype=np.int64)
    x=first_exit(minute,0,[], -1,D("1.00025"),base,0,10*STEP,"time",20*STEP)
    check("short stop is tested on modeled Ask",x["reason"]=="stop" and x["ref"]==D("1.00025"))
    x=first_exit(minute,0,[], 1,D(".999"),base,0,60,"period_end",60)
    check("exact deadline surviving minute closes",x["kind"]=="close" and x["event_ts"]==60 and not x["terminal_fallback"])
    x=first_exit(minute,0,[], 1,D(".999"),base,0,120,"period_end",120)
    check("period fallback never reads future opening",x["event_ts"]==60 and x["terminal_fallback"])
    minute=np.array([[0,1000000,1000200,999900,1000000],[30*STEP+60,1000000,1000200,999900,1000000]],dtype=np.int64)
    x=first_exit(minute,0,[],1,D(".999"),base,0,30*STEP,"time",40*STEP)
    check("time deadline counts calendar H4 slots across missing minutes",x["event_ts"]==30*STEP+60 and x["reason"]=="time" and x["kind"]=="open")
    check("flat net unit cost identity is exactly zero",(D("1.16222")-D("1.16215")-D(2)*D(".000035"))==ZERO)
    # Actual account entry cancellation, using injected completed indicator states.
    at=epoch("2024-01-01T00:00:00Z")
    p={"periods":{"full":[iso(at),iso(at+4*STEP)]},"pip_size":.0001,
       "account":{"initial_cash":10000,"risk_fraction":.01},
       "costs":{"baseline":{"spread_pips":1,"slippage_pips_per_leg":.1,
           "commission_usd_per_100000_eur_per_leg":3.5,"carry_pips_per_rollover_unit":.2}}}
    rs=toy_rows(202)
    for i,r in enumerate(rs):
        r.update(ts=at+(i-200)*STEP,rvi=Fraction(0)if i<199 else Fraction(1),signal=Fraction(0),atr14=D(".001"),ema200=D(".99"))
        r.update(first_ts=r["ts"],last_ts=r["ts"]+STEP-60)
    roll2,sess2,fri2=calendar_events(at-210*STEP,at+4*STEP)
    mm=np.array([[at+60,1000000,1000200,999900,1000000]],dtype=np.int64)
    account=replay(rs,mm,p,"primary","full",roll2,sess2,fri2,[])
    check("missing exact M1 entry opening cancels without later fill",account["metrics"]["canceled_missing_entry"]==1 and account["metrics"]["trades"]==0)
    return tests


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--protocol",type=Path,required=True)
    parser.add_argument("--evidence",type=Path)
    parser.add_argument("--raw-dir",type=Path)
    parser.add_argument("--report",type=Path,default=Path("eurusd-rvi-independent-verification.json"))
    parser.add_argument("--synthetic-only",action="store_true")
    args=parser.parse_args()
    comparison=Compare()
    report={"status":"failed","method":"Independent exact-Fraction RVI/signal and Decimal50 EMA/ATR/accounts from original M1 ZIPs; Forex accounting framework adapted from the separate TRIX verifier; no production engine import or execution", "decimal_precision":50,
            "tolerances_absolute":{"money_USD":"0.000001","quantity_EUR":"0.0000001","price_indicator_metric":"0.00000001","discrete_decisions":"exact"}}
    try:
        require(digest(args.protocol)==FROZEN,"Frozen protocol SHA256 changed")
        protocol=json.loads(args.protocol.read_text())
        report.update(protocol_sha256=FROZEN,checker_sha256=digest(Path(__file__)))
        report["synthetic_tests"]=synthetic_tests()
        if not args.synthetic_only:
            require(args.evidence is not None and args.raw_dir is not None,"Evidence and original raw directory are required")
            evidence=json.loads(args.evidence.read_text())
            report["evidence_sha256"]=digest(args.evidence)
            comparison.matching(protocol,evidence["protocol"],"protocol")
            comparison.one(FROZEN,evidence["protocol_sha256"],"protocol_sha256")
            minutes,source_quality=originals(args.raw_dir,protocol)
            rows=indicators(h4_observations(minutes))
            rolls,sessions,fridays=calendar_events(int(minutes[0,0]),max(epoch(x[1])for x in protocol["periods"].values()))
            missing,gaps=gap_quality(minutes,sessions)
            report["source_verification"]={"archives":len(PINS),"retained_minutes":len(minutes),"h4_buckets":len(rows),"raw_rows":source_quality["raw_rows_all_archives"],"identical_duplicate_rows_removed":source_quality["exact_duplicate_rows_removed"],"all_pinned_hashes_and_CRCs_passed":True}
            report["source_quality"]={k:v for k,v in gaps.items() if k!="gaps"}
            source_quality.update(gaps)
            source_quality.update(invalid_count=0,duplicate_count=0,h4_bars=len(rows),
                                  partial_h4_bars=sum(r["n"]<240 for r in rows),
                                  stale_close_h4_bars=sum(r["last_ts"]+60 != r["ts"]+STEP for r in rows),
                                  eval_bars={name:sum(epoch(window[0])<=r["ts"]<epoch(window[1])for r in rows)for name,window in protocol["periods"].items()})
            # Indicator field aliases are selected solely from output schema, not values.
            actual_rows=evidence["bars"]
            require(len(actual_rows)==len(rows),"H4 row count differs")
            aliases={"rvi":("rvi",),"signal":("signal",),"ema200":("ema200",),"atr14":("atr14",),"cross":("cross",)}
            for index,(expected,actual) in enumerate(zip(rows,actual_rows)):
                mapped={}
                for key,value in expected.items():
                    if key in aliases:
                        targets=[a for a in aliases[key] if a in actual]
                        for name in targets:mapped[name]=value
                    elif key in actual:mapped[key]=value
                comparison.matching(mapped,actual,"bars."+str(index))
                require(set(actual)<=set(mapped),"Unverified published H4 fields: "+str(set(actual)-set(mapped)))
            report["indicator_fields_compared"]=sorted(set(actual_rows[200])&{v for values in aliases.values()for v in values})
            quality_actual=evidence.get("data_quality",{})
            comparison.matching({k:v for k,v in source_quality.items()if k in quality_actual and k!="sources"},quality_actual,"data_quality")
            for i,record in enumerate(source_quality["sources"]):
                comparison.matching({key:record[key]for key in ("file","sha256","bytes","csv")},quality_actual["sources"][i],"data_quality.sources."+str(i))
            rebuilt={}
            for name in protocol["runs"]:
                variant,period=name.rsplit("_",1)
                run=replay(rows,minutes,protocol,variant,period,rolls,sessions,fridays,missing)
                rebuilt[name]=run
                published=evidence["runs"][name]
                require(set(published["metrics"])<=set(run["metrics"]),"Unverified published metrics: "+str(set(published["metrics"])-set(run["metrics"])))
                for trade in published["trades"]:
                    require(set(trade)<=set(run["trades"][0]),"Unverified published trade fields: "+str(set(trade)-set(run["trades"][0])))
                comparison.matching(run,evidence["runs"][name],"runs."+name,require_all=False)
            report["replayed_accounts"]={name:{"trades":len(run["trades"]),"close_marks":len(run["equity"]),"end_cash_USD":str(run["metrics"]["end_cash"]),"cash_identity_error_USD":str(abs(run["metrics"]["end_cash"]-decimal(protocol["account"]["initial_cash"])-sum((t["pnl"]for t in run["trades"]),ZERO)))}for name,run in rebuilt.items()}
            cash=decimal(protocol["account"]["initial_cash"])
            comparison.matching({"initial_cash":cash,"end_cash":cash,"return_pct":ZERO,"drawdown_pct":ZERO},evidence["cash_reference"],"cash_reference")
            exclusions={}
            for name,run in rebuilt.items():
                retained=[t for t in run["trades"] if not t["crosses_gap"]]
                exclusions[name]={"original_trades":len(run["trades"]),"excluded_gap_trades":len(run["trades"])-len(retained),"retained_trades":len(retained),"retained_ledger_pnl":sum((t["pnl"]for t in retained),ZERO)}
            comparison.matching(exclusions,evidence["gap_exclusion"],"gap_exclusion")
            first_early=rebuilt["primary_early"]["trades"][0]
            later=rebuilt["primary_later"]["trades"]
            chosen={"early":first_early,"later":later[0]}
            chosen["opposite"]=next((t for t in later[1:]if t["pnl"]*later[0]["pnl"]<0),later[1]if len(later)>1 else None)
            for example in evidence.get("examples",[]):
                tag=example["tag"]
                tag="opposite" if tag=="extra" else tag
                if tag in chosen and chosen[tag]is not None:
                    comparison.matching(chosen[tag],example["trade"],"examples."+tag+".trade",require_all=False)
            report["additional_checks"]={"selected_examples":len(evidence.get("examples",[])),"source_manifest_pins":len(PINS),"annual_paths":"compared","all_published_trade_metrics_bar_and_equity_fields":"independently reconstructed and compared; descriptive run strings retained","cash_reference_and_gap_exclusion":"compared","comparison_field_names":sorted(comparison.fields)}
        report["status"]="passed" if comparison.failures==0 else "failed"
    except Exception as error:
        report["fatal_error"]=type(error).__name__+": "+str(error)
    report["comparison"]={"numeric_values_compared":comparison.numeric,"exact_values_compared":comparison.exact,"failures":comparison.failures,"failure_samples":comparison.samples,"maximum_absolute_errors":{k:str(v)for k,v in comparison.max_errors.items()},"maximum_error_locations":comparison.max_locations}
    report["checked_at_utc"]=dt.datetime.now(UTC).isoformat()
    args.report.parent.mkdir(exist_ok=True,parents=True)
    args.report.write_text(json.dumps(report,indent=2,ensure_ascii=False)+"\n")
    print(json.dumps({"status":report["status"],"report":str(args.report),"comparison_failures":comparison.failures,"fatal_error":report.get("fatal_error"),"synthetic_tests":len(report.get("synthetic_tests",[]))}))
    return 0 if report["status"]=="passed" else 1


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