#!/usr/bin/env python3
"""Independent Decimal(50) verification of the frozen GBPUSD Envelopes SMA20 / Wilder ADX14 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. Percentage bands and their price comparisons use exact Fractions;
Wilder indicators, execution, sizing and cash use Decimal50 arithmetic.
"""
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 = "5267bb4717c56bd9277e87df8827bb33723e80dca62dd570b299e0f41757e3b6"
PINS = {'GBPUSD-M1-2019.zip': 'bc6d390e539d267fcd7856851db463fc098de5d7f7d732ddca75604f4a259bf2', 'GBPUSD-M1-2020.zip': '07ad9524551d1b5bc617cd6971e5a6f38156f92e7046fa368abd22cbe7d9a044', 'GBPUSD-M1-2021.zip': '5ce226e9e1cabcb8d3cab7d5c64135da2c864b0d79a559c8a08c6e1e3d47866e', 'GBPUSD-M1-2022.zip': '6c3134133d24effe9ebae1ee02c7b0db3bff8f60f92bd9add846abc54d00a86e', 'GBPUSD-M1-2023.zip': '4e7031d841a953ae76d1ba056780838bddd08e0d5eac62dd21c64b28b7b1a68b', 'GBPUSD-M1-2024.zip': '030b05b4c670c7e152bf4aa4112488c96695d2dcc2b31ca13a3b4834b8431077', 'GBPUSD-M1-2025.zip': '7b69c334eadd10568168634cff3ca37b06e5fb9057db4da9b590e2ef2034854e'}


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 "GBPUSD" 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):
    """Calculate observed-close percentage bands and independent Wilder streams."""
    closes=[r["source_close_int"] for r in rows]
    transition_ranges=[];positive_moves=[];negative_moves=[];stop_ranges=[]
    smoothed_tr=smoothed_plus=smoothed_minus=adx=atr=None
    dx_seed=[]
    for index,row in enumerate(rows):
        center=Fraction(sum(closes[index-19:index+1]),20*SCALE) if index>=19 else None
        upper=center*Fraction(201,200) if center is not None else None
        lower=center*Fraction(199,200) if center is not None else None
        tr=row["high"]-row["low"]
        plus=minus=None
        if index:
            previous=rows[index-1]
            tr=max(tr,abs(row["high"]-previous["close"]),abs(row["low"]-previous["close"]))
            up=row["high"]-previous["high"]
            down=previous["low"]-row["low"]
            plus=up if up>down and up>0 else ZERO
            minus=down if down>up and down>0 else ZERO
            transition_ranges.append(tr);positive_moves.append(plus);negative_moves.append(minus)
            if index==14:
                smoothed_tr=sum(transition_ranges,ZERO)/14
                smoothed_plus=sum(positive_moves,ZERO)/14
                smoothed_minus=sum(negative_moves,ZERO)/14
            elif index>14:
                smoothed_tr=(D(13)*smoothed_tr+tr)/14
                smoothed_plus=(D(13)*smoothed_plus+plus)/14
                smoothed_minus=(D(13)*smoothed_minus+minus)/14
        stop_ranges.append(tr)
        if index==13:
            atr=sum(stop_ranges,ZERO)/14
        elif index>13:
            atr=(D(13)*atr+tr)/14
        dp=dm=dx=None
        if smoothed_tr is not None:
            dp=HUNDRED*smoothed_plus/smoothed_tr if smoothed_tr else ZERO
            dm=HUNDRED*smoothed_minus/smoothed_tr if smoothed_tr else ZERO
            dx=HUNDRED*abs(dp-dm)/(dp+dm) if dp+dm else ZERO
            if adx is None:
                dx_seed.append(dx)
                if len(dx_seed)==14:
                    adx=sum(dx_seed,ZERO)/14
            else:
                adx=(D(13)*adx+dx)/14
        row.update(sma20=center,upper=upper,lower=lower,
                   sma20_exact=None if center is None else str(center),
                   upper_exact=None if upper is None else str(upper),
                   lower_exact=None if lower is None else str(lower),
                   adx_tr=None if index==0 else tr,dm_plus=plus,dm_minus=minus,
                   smoothed_tr=smoothed_tr,smoothed_dm_plus=smoothed_plus,smoothed_dm_minus=smoothed_minus,
                   di_plus=dp,di_minus=dm,dx=dx,adx14=adx,atr14=atr)
        row["raw_cross"]=crossing(rows,index)
        row["cross"]=entry_cross(rows,index)
        row["adx_pass"]=adx is not None and adx>=25
        price=Fraction(row["source_close_int"],SCALE)
        row["exit_long"]=center is not None and price<=center
        row["exit_short"]=center is not None and price>=center
    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
    bands=[previous.get("upper"),previous.get("lower"),current.get("upper"),current.get("lower")]
    if any(value is None for value in bands):
        return 0
    old=Fraction(previous["source_close_int"],SCALE)
    new=Fraction(current["source_close_int"],SCALE)
    if old<=previous["upper"] and new>current["upper"]:
        return 1
    if old>=previous["lower"] and new<current["lower"]:
        return -1
    return 0


def entry_cross(rows,index):
    row=rows[index]
    if index<27 or row.get("adx14") 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_gbp_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(adx, variant):
    return variant=="no_adx" or adx>=25


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["close"] is not None and row["sma20"] is not None:
                exit_level = row["close"] <= row["sma20"] if direction == 1 else row["close"] >= row["sma20"]
                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(row["adx14"],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-GBP 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["close"] is not None and r["sma20"] is not None
                              and (r["close"] <= r["sma20"] if direction==1 else r["close"] >= r["sma20"])),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_sma20":row["sma20"], "signal_upper":row["upper"], "signal_lower":row["lower"], "signal_adx":row["adx14"], "signal_di_plus":row["di_plus"], "signal_di_minus":row["di_minus"],
                 "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(100))
    check("SMA20 first index19, stopATR13, DI-DX14 and ADX27",all(next(i for i,r in enumerate(rows) if r[k] is not None)==v for k,v in (("sma20",19),("atr14",13),("di_plus",14),("dx",14),("adx14",27))))
    check("constant observed prices give zeroDM-DX-ADX",all(r["di_plus"]==0 and r["di_minus"]==0 and r["dx"]==0 for r in rows[14:]) and all(r["adx14"]==0 for r in rows[27:]))
    check("constant closes produce no breakout",all(r["cross"]==0 for r in rows))
    check("percentage halfwidth is0.5percent and fullwidth1percent",rows[19]["upper"]==Fraction(201,200) and rows[19]["lower"]==Fraction(199,200) and rows[19]["upper"]-rows[19]["lower"]==Fraction(1,100))
    doubled=toy_rows(30)
    for r in doubled:
        for field in ("open","high","low","close"):r[field]*=2
        for field in ("source_open_int","source_high_int","source_low_int","source_close_int"):r[field]*=2
    doubled=indicators(doubled)
    check("halfwidth scales with SMA instead of fixedpriceunits",doubled[19]["upper"]==Fraction(201,100) and doubled[19]["lower"]==Fraction(199,100))
    pair=toy_rows(2)
    for r in pair:r.update(upper=Fraction(201,200),lower=Fraction(199,200))
    pair[0]["source_close_int"]=1005000;pair[1]["source_close_int"]=1006000
    check("previous upperband equality allows long breakout",crossing(pair,1)==1)
    pair[1]["source_close_int"]=1005000
    check("current upperband equality rejects long breakout",crossing(pair,1)==0)
    pair[0]["source_close_int"]=995000;pair[1]["source_close_int"]=994000
    check("previous lowerband equality allows short breakout",crossing(pair,1)==-1)
    pair[1]["source_close_int"]=995000
    check("current lowerband equality rejects short breakout",crossing(pair,1)==0)
    pair[0]["source_close_int"]=1000000;pair[1]["source_close_int"]=1000000
    pair[1]["source_high_int"]=1100000
    check("high touch without close breakout is notentry",crossing(pair,1)==0)
    pair[1]["source_close_int"]=1006000;pair[1]["ts"]+=STEP
    check("scheduled gap blocks otherwisevalid pricecross",crossing(pair,1)==0)
    check("ADX threshold includes exact25",entry_gate(D(25),"primary"))
    check("ADX below25fails without rounding tolerance",not entry_gate(D("24.999999999999999999999"),"primary"))
    check("control removes only ADX threshold",entry_gate(D(0),"no_adx"))
    check("ADX gate imposes no DI direction or rising condition",entry_gate(D(25),"primary"))
    tied=toy_rows(30)
    tied[1].update(high=D("1.02"),low=D(".98"),source_high_int=1020000,source_low_int=980000)
    tied=indicators(tied)
    check("positive equal directional moves bothbecomezero",tied[1]["dm_plus"]==0 and tied[1]["dm_minus"]==0)
    trend=toy_rows(35)
    for i,r in enumerate(trend):
        for field in ("open","high","low","close"):r[field]+=D(i)/100
        for field in ("source_open_int","source_high_int","source_low_int","source_close_int"):r[field]+=i*10000
    trend=indicators(trend)
    check("winnerDM keeps positiveupmove and clearsminus",trend[1]["dm_plus"]==D(".01") and trend[1]["dm_minus"]==0)
    check("ADX first28-observation result is100forpersistentdirection",trend[27]["adx14"]==100)
    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("flat smoothedTR yields DI-DX-ADXzero",flat[14]["di_plus"]==0 and flat[14]["di_minus"]==0 and flat[14]["dx"]==0 and flat[27]["adx14"]==0)
    check("zero stopATR blocks eitherentry variant",all(r["cross"]==0 for r in flat))
    distinct=toy_rows(30)
    distinct[0].update(high=D(2),low=D(".5"),source_high_int=2000000,source_low_int=500000)
    distinct=indicators(distinct)
    check("stopATR includes first range but ADXtransitions donot",distinct[13]["atr14"]==(D("1.5")+13*D(".02"))/14 and distinct[14]["smoothed_tr"]==D(".02"))
    check("ADX predecessor bar has no transition",distinct[0]["adx_tr"] is None and distinct[0]["dm_plus"] is None and distinct[0]["dm_minus"] is None)
    gapped=toy_rows(100)
    for r in gapped[25:]:r["ts"]+=3*STEP
    gapped=indicators(gapped)
    check("bands and Wilder state continue through observedgaps",gapped[27]["sma20"]==1 and gapped[27]["adx14"]==0)
    check("center equality exits before ADX and entrywarmup",rows[19]["exit_long"] and rows[19]["exit_short"] and rows[19]["adx14"] is None)
    check("shared entry gate excludes earlierthan28 observations",all(r["cross"]==0 for r in trend[:27]))
    unready=toy_rows(28)
    for r in unready:r.update(upper=Fraction(201,200),lower=Fraction(199,200),atr14=D(".01"),adx14=None)
    unready[-1]["source_close_int"]=1010000
    check("control retains definedADX warmup requirement",crossing(unready,27)==1 and entry_cross(unready,27)==0)
    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,"close":D(1),"sma20":D(0)},{"ts":STEP,"close":D(-1),"sma20":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)
    center_rows=[{"ts":0,"close":D("1.003"),"sma20":Fraction(1)},
                 {"ts":STEP,"close":D("1.002"),"sma20":Fraction(1)}]
    center_minutes=np.array([[0,1003000,1004000,1002000,1003000],
                             [2*STEP,1002000,1003000,1001000,1002000]],dtype=np.int64)
    centered=first_exit(center_minutes,0,center_rows,1,D(".999"),base,0,2*STEP+60,"time",3*STEP)
    check("return inside outerband alone does notexit",centered["reason"]=="time" and centered["kind"]=="close")
    center_rows[1]["close"]=D(1)
    centered=first_exit(center_minutes,0,center_rows,1,D(".999"),base,0,2*STEP+60,"time",3*STEP)
    check("center equality queues exit without ADXorATR fields",centered["reason"]=="signal_exit" and centered["event_ts"]==2*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_gbp_per_leg":3.5,"carry_pips_per_rollover_unit":.2}}}
    rs=toy_rows(30)
    for i,r in enumerate(rs):
        close=1000000 if i<27 else 1010000
        r.update(ts=at+(i-28)*STEP,source_close_int=close,close=D(close)/SCALE,
                 upper=Fraction(201,200),lower=Fraction(199,200),sma20=Fraction(1),
                 atr14=D(".001"),adx14=D(30),di_plus=D(10),di_minus=D(40))
        r.update(first_ts=r["ts"],last_ts=r["ts"]+STEP-60)
    roll2,sess2,fri2=calendar_events(at-35*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 laterfill",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("gbpusd-envelopes-independent-verification.json"))
    parser.add_argument("--synthetic-only",action="store_true")
    args=parser.parse_args()
    comparison=Compare()
    report={"status":"failed","method":"Independent exact-Fraction SMA20 percentage bands and Decimal50 Wilder ADX/ATR/accounts from original M1 ZIPs; account framework adapted from separate RVI/TRIX verifiers; no production engine import or execution", "decimal_precision":50,
            "tolerances_absolute":{"money_USD":"0.000001","quantity_GBP":"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={"sma20_exact":("sma_exact",),"adx14":("adx",),"adx_pass":("adx_strong",)}
            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[30])&{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())
