#!/usr/bin/env python3
"""Independent original-ZIP SOLUSDT Aroon25 / CCI20 research rebuild.

Written from the frozen economic protocol and a field-only serialization contract.
It imports no project modules, primary arrays, old strategies or derived outputs.
All source/CCI arithmetic is exact; ATR and the complete cash ledger use Decimal50.
Before any synthetic or historical arithmetic the executable, protocol and manifest
are copied and hash-locked. Historical output is locked before counterpart access.
"""
from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import io
import json
import re
import shutil
import sys
import zipfile
from collections import Counter
from datetime import datetime, timezone
from decimal import Decimal, getcontext
from fractions import Fraction
from pathlib import Path

getcontext().prec = 50
D = Decimal
F = Fraction
STEP = 14400
SCALE = 100000000
PROTOCOL_SHA = 'f37c159506d3303b8aa655dd1ef08467d1b67a277916f24719aa2809fbced339'
MANIFEST_SHA = 'fa421980255e7c0790fe6cffeb9bf6ac15b8fecc693eae4c71f49c0c9a36ae4d'
FEE_SLIP = {'base': (F(1, 1000), F(1, 2000)),
            'zero': (F(0), F(0)), 'higher': (F(1, 500), F(1, 1000))}


def now():
    return datetime.now(timezone.utc).isoformat()


def digest(data):
    return hashlib.sha256(data).hexdigest()


def read_json(p):
    return json.loads(Path(p).read_text())


def decimal_fraction(value):
    return D(value.numerator) / D(value.denominator)


def decimal_price(integer):
    return D(integer) / D(SCALE)


def iso_time(value):
    return int(datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp())


def json_bytes(value, precise=False):
    def encode(obj):
        if isinstance(obj, D):
            return str(obj) if precise else float(obj)
        raise TypeError(type(obj).__name__)
    return (json.dumps(value, ensure_ascii=False, separators=(',', ':'),
                       allow_nan=False, default=encode) + '\n').encode()


def write_json(path, value):
    Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2,
                                    allow_nan=False) + '\n')


def lock_code(directory, protocol_path, manifest_path):
    """No indicator, synthetic price or account operation precedes this call."""
    directory.mkdir(parents=True, exist_ok=True)
    code = Path(__file__).resolve().read_bytes()
    protocol_raw = protocol_path.read_bytes()
    manifest_raw = manifest_path.read_bytes()
    if digest(protocol_raw) != PROTOCOL_SHA or digest(manifest_raw) != MANIFEST_SHA:
        raise ValueError('Frozen protocol/manifest hash mismatch')
    record = {'stage': 'locked_before_first_synthetic_or_historical_calculation',
              'at_utc': now(), 'code_sha256': digest(code),
              'protocol_sha256': digest(protocol_raw),
              'manifest_sha256': digest(manifest_raw),
              'primary_code_or_results_read': False,
              'historical_source_rows_read': False}
    path = directory / 'independent-code-lock.json'
    if path.exists():
        old = read_json(path)
        for key in ('code_sha256', 'protocol_sha256', 'manifest_sha256'):
            if old[key] != record[key]:
                raise ValueError('Existing code lock differs; preserve it and use a new run directory')
        return old
    snapshot = directory / ('frozen-' + record['code_sha256'] + '.py')
    with snapshot.open('xb') as stream:
        stream.write(code)
    record['immutable_code_snapshot'] = str(snapshot)
    with path.open('x') as stream:
        json.dump(record, stream, indent=2)
        stream.write('\n')
    return record


def scaled_integer(text, positive=False):
    value = D(text)
    if not value.is_finite() or value < 0 or (positive and value <= 0):
        raise ValueError('Invalid source price/volume')
    scaled = value * SCALE
    if scaled != scaled.to_integral_value():
        raise ValueError('Source value exceeds exact1e8 precision')
    return int(scaled)


def decode_row(fields, month):
    if len(fields) != 12:
        raise ValueError('Original source row must have12 fields')
    if not fields[0].isdigit() or not fields[6].isdigit():
        raise ValueError('Noninteger source timestamp')
    raw_open, raw_close = int(fields[0]), int(fields[6])
    unit = 1000000 if raw_open >= 100000000000000 else 1000
    if raw_open % unit:
        raise ValueError('Fractional opening second')
    ts = raw_open // unit
    if ts % STEP or datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m') != month:
        raise ValueError('Off-grid opening or archive-month mismatch')
    ints = [scaled_integer(fields[i], positive=True) for i in range(1, 5)]
    o, h, l, c = ints
    if not (0 < l <= min(o, c) <= max(o, c) <= h):
        raise ValueError('Invalid source OHLC ordering')
    volume = scaled_integer(fields[5])
    return dict(ts=ts, source_open_raw=raw_open, source_close_raw=raw_close,
                timestamp_scale=unit, open=decimal_price(o), high=decimal_price(h),
                low=decimal_price(l), close=decimal_price(c), volume=decimal_price(volume),
                open_int=o, high_int=h, low_int=l, close_int=c, volume_int=volume,
                canonical=raw_close == (ts + STEP) * unit - 1,
                source_fields=list(fields))


def load_originals(raw, manifest, protocol):
    selected = protocol['source_selection']['files']
    descriptions = manifest['files']
    if len(selected) != 65 or [v['file'] for v in descriptions] != selected:
        raise ValueError('Expected precisely the frozen65 original archives')
    bars, sources, gaps = [], [], []
    units = Counter()
    noncanonical = []
    fingerprint = hashlib.sha256()
    previous = None
    for spec in descriptions:
        archive_path = raw / spec['file']
        original = archive_path.read_bytes()
        if len(original) != spec['bytes'] or digest(original) != spec['sha256']:
            raise ValueError('Archive byte/hash mismatch: ' + spec['file'])
        side = (raw / spec['checksum_file']).read_bytes()
        if digest(side) != spec['checksum_sha256']:
            raise ValueError('CHECKSUM sidecar hash mismatch')
        fields = side.decode('ascii').split()
        if (len(fields) != 2 or fields[0].lower() != spec['sha256'] or
                fields[1].lstrip('*') != spec['file']):
            raise ValueError('CHECKSUM named digest mismatch')
        month_match = re.fullmatch(r'SOLUSDT-4h-(\d{4}-\d{2})\.zip', spec['file'])
        if not month_match:
            raise ValueError('Unexpected archive name')
        local_previous = None
        count = 0
        with zipfile.ZipFile(io.BytesIO(original)) as z:
            if z.namelist() != [spec['csv_member']] or z.testzip() is not None:
                raise ValueError('ZIP member or CRC mismatch')
            with z.open(spec['csv_member']) as compressed:
                text = io.TextIOWrapper(compressed, encoding='ascii', newline='')
                for strings in csv.reader(text):
                    b = decode_row(strings, month_match[1])
                    ts = b['ts']
                    if local_previous is not None and ts <= local_previous:
                        raise ValueError('Duplicate/nonincreasing archive timestamp')
                    if previous is not None:
                        if ts <= previous:
                            raise ValueError('Duplicate/nonincreasing normalized timestamp')
                        if ts != previous + STEP:
                            gaps.append(dict(left=previous, right=ts,
                                             missing=(ts - previous) // STEP - 1))
                    fingerprint.update((','.join(strings) + '\n').encode('ascii'))
                    bars.append(b)
                    units[str(b['timestamp_scale'])] += 1
                    if not b['canonical']:
                        noncanonical.append(ts)
                    local_previous = previous = ts
                    count += 1
        sources.append(dict(file=spec['file'], sha256=spec['sha256'],
                            rows=count, crc_verified=True))
    quality = dict(rows=len(bars), source_files=len(descriptions), sources=sources,
                   gaps=gaps, missing_bars=sum(v['missing'] for v in gaps),
                   noncanonical_closes=noncanonical,
                   timestamp_units=dict(units),
                   zero_volume_rows=sum(b['volume_int'] == 0 for b in bars),
                   zero_range_rows=sum(b['high_int'] == b['low_int'] for b in bars),
                   source_fingerprint_sha256=fingerprint.hexdigest())
    return bars, quality


def ratio_fields(bar, prefix, value):
    bar[prefix] = None if value is None else float(value)
    bar[prefix + '_num'] = None if value is None else str(value.numerator)
    bar[prefix + '_den'] = None if value is None else str(value.denominator)


def annotate(source_bars):
    bars = [dict(b) for b in source_bars]
    segment = []
    tr_history = []
    atr = None
    previous_ts = None
    for i, b in enumerate(bars):
        if not b['canonical'] or previous_ts is None or b['ts'] != previous_ts + STEP:
            segment, tr_history, atr = [], [], None
        b.update(canonical_run=0, atr14=None, eligible=False,
                 transition=None, prior_both_low=None, cci_gate=None,
                 exit_level=None, current_high_ties_previous=None,
                 aroon_up=None, aroon_down=None, age_high=None, age_low=None,
                 window_high_int=None, window_low_int=None,
                 window_high=None, window_low=None)
        for prefix in ('tp', 'mean_tp', 'mad', 'cci'):
            ratio_fields(b, prefix, None)
        if not b['canonical']:
            previous_ts = b['ts']
            continue
        tr = b['high'] - b['low']
        if segment:
            pc = segment[-1]['close']
            tr = max(tr, abs(b['high'] - pc), abs(b['low'] - pc))
        tr_history.append(tr)
        segment.append(b)
        run = len(segment)
        b['canonical_run'] = run
        if run == 14:
            atr = sum(tr_history, D(0)) / 14
        elif run > 14:
            atr = (13 * atr + tr) / 14
        b['atr14'] = atr
        ratio_fields(b, 'tp', F(b['high_int'] + b['low_int'] + b['close_int'], 3 * SCALE))
        if run >= 20:
            zs = [r['high_int'] + r['low_int'] + r['close_int'] for r in segment[-20:]]
            total = sum(zs)
            absolute = sum(abs(20 * z - total) for z in zs)
            ratio_fields(b, 'mean_tp', F(total, 60 * SCALE))
            ratio_fields(b, 'mad', F(absolute, 1200 * SCALE))
            if absolute:
                cci = F(4000 * (20 * zs[-1] - total), 3 * absolute)
                ratio_fields(b, 'cci', cci)
                b['cci_gate'] = cci > 100
        if run >= 26:
            w = segment[-26:]
            maximum = max(r['high_int'] for r in w)
            minimum = min(r['low_int'] for r in w)
            # Reverse traversal makes equal extrema choose their most recent occurrence.
            ah = next(age for age, r in enumerate(reversed(w)) if r['high_int'] == maximum)
            al = next(age for age, r in enumerate(reversed(w)) if r['low_int'] == minimum)
            up, down = 4 * (25 - ah), 4 * (25 - al)
            b.update(aroon_up=up, aroon_down=down, age_high=ah, age_low=al,
                     window_high_int=maximum, window_low_int=minimum,
                     window_high=decimal_price(maximum), window_low=decimal_price(minimum),
                     current_high_ties_previous=b['high_int'] == max(r['high_int'] for r in w[:-1]),
                     exit_level=up < 50)
        if run >= 27:
            prior = segment[-2]
            b['prior_both_low'] = prior['aroon_up'] < 50 and prior['aroon_down'] < 50
            b['transition'] = b['prior_both_low'] and b['aroon_up'] == 100 and b['aroon_down'] < 50
        b['eligible'] = bool(run >= 100 and atr is not None and atr > 0 and
                             b['cci'] is not None and run >= 27)
        previous_ts = b['ts']
    return bars


def signal(model, b):
    return bool(b['eligible'] and b['transition'] and
                (model == 'no_cci' or b['cci_gate'] is True))


def make_candidate(b, prior, flat, model, end):
    action = ('held' if not flat else 'outside_period' if b['ts'] + STEP >= end
              else 'queued' if signal(model, b) else 'filter_rejected')
    return dict(ts=b['ts'], available=b['ts'] + STEP,
                aroon_up=b['aroon_up'], aroon_down=b['aroon_down'],
                prev_aroon_up=prior['aroon_up'], prev_aroon_down=prior['aroon_down'],
                cci=b['cci'], cci_gate=b['cci_gate'], flat_after_events=flat,
                action=action)


def initialize_position(b, origin, prior, balance, fee, slip):
    o = decimal_price(b['open_int'])
    entry = o * (1 + slip)
    stop = entry - 2 * origin['atr14']
    if stop <= 0 or stop >= o:
        return None
    loss = entry * (1 + fee) - stop * (1 - slip) * (1 - fee)
    if loss <= 0:
        return None
    risk_quantity = balance * D('0.01') / loss
    cash_quantity = balance / (entry * (1 + fee))
    quantity = min(risk_quantity, cash_quantity)
    # When capped, spending the full flat cash is an exact economic identity.
    remaining = D(0) if cash_quantity <= risk_quantity else balance - quantity * entry * (1 + fee)
    if quantity <= 0 or remaining < 0:
        raise AssertionError('Cash-funded entry cannot borrow')
    return dict(signal_bar_ts=origin['ts'], signal_ts=origin['ts'] + STEP,
                entry_ts=b['ts'], entry_ref=o, entry_ref_int=b['open_int'], entry=entry,
                stop=stop, qty=quantity, risk_cash=quantity * loss, unit_loss=loss,
                cash_before=balance, cash_capped=cash_quantity < risk_quantity,
                signal_aroon_up=origin['aroon_up'], signal_aroon_down=origin['aroon_down'],
                signal_prev_aroon_up=prior['aroon_up'], signal_prev_aroon_down=prior['aroon_down'],
                signal_cci=origin['cci'], signal_atr14=origin['atr14'],
                crosses_gap=False, touches_noncanonical=not b['canonical'],
                _cash=remaining, _deadline=b['ts'] + 30 * STEP,
                _aging_due=None, _last_seen=b['ts'])


def liquidate(position, b, reason, precision, fee_f, slip_f, end):
    fee, slip = decimal_fraction(fee_f), decimal_fraction(slip_f)
    if precision == 'open':
        reference, source_integer = decimal_price(b['open_int']), b['open_int']
        event_ts = b['ts']
    elif precision == 'close':
        reference, source_integer = decimal_price(b['close_int']), b['close_int']
        event_ts = b['ts'] + STEP
    else:
        reference, source_integer = position['stop'], None
        event_ts = b['ts']
    sale = reference * (1 - slip)
    if reason == 'stop':
        pnl = -position['risk_cash']
        sign = -1
    else:
        unit = (F(source_integer, SCALE) * (1 - slip_f) * (1 - fee_f) -
                F(position['entry_ref_int'], SCALE) * (1 + slip_f) * (1 + fee_f))
        pnl = position['qty'] * decimal_fraction(unit)
        sign = (unit > 0) - (unit < 0)
    fees = position['qty'] * (position['entry'] + sale) * fee
    cash = position['cash_before'] + pnl
    sold_cash = position['_cash'] + position['qty'] * sale * (1 - fee)
    # This is a high-precision conservation check, not a net-PnL sign tolerance.
    if abs(cash - sold_cash) > D('1e-35'):
        raise AssertionError('Reserved cash + net sale does not reconcile')
    trade = {k: v for k, v in position.items() if not k.startswith('_')}
    trade.update(exit_bar_ts=b['ts'], exit_event_ts=event_ts, exit_precision=precision,
                 exit_ref=reference, exit=sale, reason=reason, fees=fees, pnl=pnl,
                 pnl_sign=sign, net_r=pnl / position['risk_cash'],
                 delayed_aroon_exit=bool(reason == 'aroon_exit' and b['ts'] > position['_aging_due']),
                 partial_close_proxy=precision == 'close' and not b['canonical'],
                 early_terminal_proxy=reason == 'period_end' and b['ts'] + STEP < end)
    costs = dict(entry_slippage=position['qty'] * (position['entry'] - position['entry_ref']),
                 exit_slippage=position['qty'] * (reference - sale),
                 turnover_usdt=position['qty'] * (position['entry'] + sale))
    return trade, cash, costs


def annual_marks(equity, initial):
    years = {}
    for point in equity:
        years[datetime.fromtimestamp(point['bar_ts'], timezone.utc).year] = point['equity']
    previous = initial
    result = []
    for year, ending in years.items():
        result.append(dict(year=year, return_pct=100 * (ending / previous - 1)))
        previous = ending
    return result


def run_account(bars, model, cost, period, start, end, initial=D(10000)):
    fee_f, slip_f = FEE_SLIP[cost]
    fee, slip = decimal_fraction(fee_f), decimal_fraction(slip_f)
    balance = initial
    position = None
    pending = None
    trades, equity, candidates = [], [], []
    all_costs = Counter()
    canceled = rejected = occupied = 0
    peak, largest_dd = initial, D(0)
    indexes = [i for i, b in enumerate(bars) if start <= b['ts'] < end]
    prior_index = next((i for i, b in enumerate(bars) if b['ts'] + STEP == start), None)
    if prior_index is not None:
        b = bars[prior_index]
        if b['eligible'] and b['transition']:
            prior = bars[prior_index - 1]
            candidates.append(make_candidate(b, prior, True, model, end))
            if signal(model, b) and start < end:
                pending = prior_index
    final_index = indexes[-1] if indexes else None
    for index in indexes:
        b = bars[index]
        held_at_open = position is not None
        exited_at_open = False
        if position is not None:
            if b['ts'] != position['_last_seen'] + STEP:
                position['crosses_gap'] = True
            position['touches_noncanonical'] |= not b['canonical']
            position['_last_seen'] = b['ts']
            opening_reason = None
            if b['open'] <= position['stop']:
                opening_reason = 'stop_gap'
            elif position['_aging_due'] is not None:
                opening_reason = 'aroon_exit'
            elif b['ts'] >= position['_deadline']:
                opening_reason = 'time_delayed'
            if opening_reason:
                trade, balance, costs = liquidate(position, b, opening_reason, 'open', fee_f, slip_f, end)
                trades.append(trade)
                all_costs.update(costs)
                position = None
                exited_at_open = True
        entered_here = False
        if pending is not None:
            due = bars[pending]['ts'] + STEP
            if due < b['ts']:
                canceled += 1
                pending = None
            elif due == b['ts']:
                if position is None and not exited_at_open:
                    position = initialize_position(b, bars[pending], bars[pending - 1], balance, fee, slip)
                    if position is None:
                        rejected += 1
                    else:
                        entered_here = True
                pending = None
        occupied += int(held_at_open or entered_here)
        if position is not None:
            reason = precision = None
            if b['low'] <= position['stop']:
                reason, precision = 'stop', 'within_4h'
            elif b['ts'] + STEP == position['_deadline']:
                reason, precision = 'time', 'close'
            elif index == final_index:
                reason, precision = 'period_end', 'close'
            if reason:
                trade, balance, costs = liquidate(position, b, reason, precision, fee_f, slip_f, end)
                trades.append(trade)
                all_costs.update(costs)
                position = None
        if position is None:
            marked = balance
        else:
            marked = position['_cash'] + position['qty'] * b['close'] * (1 - slip) * (1 - fee)
        peak = max(peak, marked)
        dd = 100 * (peak - marked) / peak
        largest_dd = max(largest_dd, dd)
        equity.append(dict(ts=b['ts'] + STEP, bar_ts=b['ts'], equity=marked, drawdown_pct=dd))
        if position is not None and b['exit_level'] is True and position['_aging_due'] is None:
            position['_aging_due'] = b['ts'] + STEP
        if b['eligible'] and b['transition']:
            candidate = make_candidate(b, bars[index - 1], position is None, model, end)
            candidates.append(candidate)
            if candidate['action'] == 'queued':
                pending = index
    if pending is not None and bars[pending]['ts'] + STEP < end:
        canceled += 1
    if position is not None:
        raise AssertionError('Final in-period observed close must liquidate')
    if equity and equity[-1]['equity'] != balance:
        raise AssertionError('Terminal equity must equal final cash')
    positive = sum((t['pnl'] for t in trades if t['pnl_sign'] > 0), D(0))
    negative = sum((t['pnl'] for t in trades if t['pnl_sign'] < 0), D(0))
    count = len(trades)
    metrics = dict(return_pct=100 * (balance / initial - 1), end_cash=balance,
                   drawdown_pct=largest_dd, trades=count,
                   wins=sum(t['pnl_sign'] > 0 for t in trades),
                   losses=sum(t['pnl_sign'] < 0 for t in trades),
                   zero_trades=sum(t['pnl_sign'] == 0 for t in trades),
                   profit_factor=positive / abs(negative) if negative else None,
                   mean_r=sum((t['net_r'] for t in trades), D(0)) / count if count else None,
                   fees=sum((t['fees'] for t in trades), D(0)),
                   exposure_pct=D(100 * occupied) / len(indexes) if indexes else D(0),
                   cash_capped=sum(t['cash_capped'] for t in trades),
                   canceled_missing_entry=canceled, rejected_entry=rejected,
                   gap_trades=sum(t['crosses_gap'] for t in trades),
                   noncanonical_trades=sum(t['touches_noncanonical'] for t in trades),
                   delayed_aroon_exits=sum(t['delayed_aroon_exit'] for t in trades),
                   partial_close_proxies=sum(t['partial_close_proxy'] for t in trades),
                   early_terminal_proxies=sum(t['early_terminal_proxy'] for t in trades),
                   entry_slippage=D(all_costs['entry_slippage']),
                   exit_slippage=D(all_costs['exit_slippage']),
                   modeled_slippage=D(all_costs['entry_slippage']) + D(all_costs['exit_slippage']),
                   turnover_usdt=D(all_costs['turnover_usdt']),
                   turnover=D(all_costs['turnover_usdt']) / initial)
    return dict(model=model, cost=cost, period=period, start_ts=start, end_ts=end,
                fee=fee, slippage=slip, metrics=metrics, trades=trades,
                equity=equity, annual=annual_marks(equity, initial), candidates=candidates)


def buy_hold(bars, period, start, end, initial=D(10000)):
    selected = [b for b in bars if start <= b['ts'] < end]
    if not selected:
        return dict(period=period, available=False,
                    metrics=dict(return_pct=D(0), end_cash=initial, drawdown_pct=D(0), exposure_pct=D(0)),
                    equity=[], entry_ts=None, exit_ts=None, entry_ref=None, entry=None,
                    exit_ref=None, exit=None, qty=None, entry_fee=D(0), exit_fee=D(0), fees=D(0),
                    partial_close_proxy=False, early_terminal_proxy=False)
    fee_f, slip_f = FEE_SLIP['base']
    fee, slip = decimal_fraction(fee_f), decimal_fraction(slip_f)
    first, last = selected[0], selected[-1]
    entry = decimal_price(first['open_int']) * (1 + slip)
    qty = initial / (entry * (1 + fee))
    exit_fill = decimal_price(last['close_int']) * (1 - slip)
    net_unit = (F(last['close_int'], SCALE) * (1 - slip_f) * (1 - fee_f) -
                F(first['open_int'], SCALE) * (1 + slip_f) * (1 + fee_f))
    ending = initial + qty * decimal_fraction(net_unit)
    entry_fee, exit_fee = qty * entry * fee, qty * exit_fill * fee
    points = []
    peak, dd_max = initial, D(0)
    for b in selected:
        marked = ending if b is last else qty * b['close'] * (1 - slip) * (1 - fee)
        peak = max(peak, marked)
        dd = 100 * (peak - marked) / peak
        dd_max = max(dd_max, dd)
        points.append(dict(ts=b['ts'] + STEP, bar_ts=b['ts'], equity=marked, drawdown_pct=dd))
    return dict(period=period, available=True,
                metrics=dict(return_pct=100 * (ending / initial - 1), end_cash=ending,
                             drawdown_pct=dd_max, exposure_pct=D(100)), equity=points,
                entry_ts=first['ts'], exit_ts=last['ts'] + STEP,
                entry_ref=decimal_price(first['open_int']), entry=entry,
                exit_ref=decimal_price(last['close_int']), exit=exit_fill, qty=qty,
                entry_fee=entry_fee, exit_fee=exit_fee, fees=entry_fee + exit_fee,
                partial_close_proxy=not last['canonical'],
                early_terminal_proxy=last['ts'] + STEP < end)


def gallery(bars, runs):
    early = runs['primary_base_early']['trades']
    later = runs['primary_base_later']['trades']
    first = later[0] if later else None
    third = None
    third_kind = 'unavailable'
    if first is not None:
        if first['pnl_sign']:
            third = next((t for t in later[1:] if t['pnl_sign'] == -first['pnl_sign']), None)
            if third is not None:
                third_kind = 'opposite_sign'
        if third is None and len(later) > 1:
            third, third_kind = later[1], 'next_later'
    indexes = {b['ts']: i for i, b in enumerate(bars)}
    result = []
    for tag, trade, kind in [('early', early[0] if early else None, 'first_chronological'),
                             ('later', first, 'first_chronological'), ('opposite', third, third_kind)]:
        if trade is None:
            result.append(dict(tag=tag, available=False, selection_kind='unavailable'))
        else:
            i = indexes[trade['signal_bar_ts']]
            j = indexes[trade['exit_bar_ts']]
            result.append(dict(tag=tag, available=True, selection_kind=kind, trade=trade,
                               bars=bars[max(0, i - 20):j + 4]))
    return result


def synthetic_bar(ts, o='100', h='101', l='99', c='100', canonical=True):
    values = [str(ts * 1000), str(o), str(h), str(l), str(c), '0',
              str((ts + STEP) * 1000 - (1 if canonical else 2)), '0', '0', '0', '0', '0']
    return decode_row(values, datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m'))


def execution_bars(n=4, base=1704067200, updates=None):
    """Explicit indicator fixtures isolate complete event/fee accounts from indicator tests."""
    updates = updates or {}
    result = []
    for i in range(n):
        changes = dict(updates.get(i, {}))
        price = {k: changes.pop(k) for k in ('o', 'h', 'l', 'c', 'canonical') if k in changes}
        b = synthetic_bar(base + i * STEP, **price)
        b.update(canonical_run=100, atr14=D(1), eligible=False, transition=False,
                 prior_both_low=True, cci_gate=True, exit_level=False,
                 aroon_up=100, aroon_down=0, cci=200.0)
        b.update(changes)
        result.append(b)
    return result


def boundary_tests():
    results = []
    def check(ok, name):
        if not ok:
            raise AssertionError('Boundary test failed: ' + name)
        results.append(name)
    base = 1704067200
    equal = annotate([synthetic_bar(base + i * STEP) for i in range(26)])[-1]
    check(equal['age_high'] == equal['age_low'] == 0, 'most_recent_extrema_ties_current_inclusive26')
    check(equal['aroon_up'] == equal['aroon_down'] == 100, 'integer_aroon100_for_equal_high_and_low')
    check(equal['current_high_ties_previous'] is True, 'equal_high_is_not_strict_new_high')
    pattern = [synthetic_bar(base + i * STEP, h='120' if i in (12, 26) else '101',
                             l='80' if i == 12 else '99') for i in range(27)]
    pattern = annotate(pattern)
    check(pattern[-2]['aroon_up'] == pattern[-2]['aroon_down'] == 48,
          'strict_below50_equals48_age13')
    check(pattern[-1]['transition'] is True and pattern[-1]['current_high_ties_previous'] is True,
          'transition_can_use_equal_current_window_high')
    check(pattern[-1]['eligible'] is False, 'transition_is_separate_from_common_warmup_mask')
    tps = [90, 90, 110, 107] + [100] * 15 + [103]
    exact = annotate([synthetic_bar(base + i * STEP, o=str(tp), h=str(tp + 1),
                                   l=str(tp - 1), c=str(tp)) for i, tp in enumerate(tps)])[-1]
    check((exact['cci_num'], exact['cci_den']) == ('100', '1') and exact['cci_gate'] is False,
          'exact_CCI100_equality_rejects_before_rounding')
    check((exact['mean_tp_num'], exact['mean_tp_den']) == ('100', '1') and exact['mad'] == 2,
          'CCI_current_same_mean_MAD_exact')
    flat_tp = annotate([synthetic_bar(base + i * STEP) for i in range(101)])
    check(flat_tp[-1]['mad'] == 0 and flat_tp[-1]['cci'] is None and flat_tp[-1]['cci_gate'] is None,
          'nonflat_candles_with_flat_TP_MAD0_remain_unavailable')
    check(flat_tp[-1]['atr14'] == D(2) and flat_tp[-1]['eligible'] is False,
          'unavailable_CCI_blocks_both_models_even_positive_ATR')
    trended = annotate([synthetic_bar(base + i * STEP, o=str(100 + i), h=str(101 + i),
                                     l=str(99 + i), c=str(100 + i)) for i in range(101)])
    check(not trended[98]['eligible'] and trended[99]['eligible'] and trended[99]['canonical_run'] == 100,
          'run99_to100_prior_run99_allowed')
    check(trended[98]['cci_gate'] is True and trended[99]['cci_gate'] is True,
          'current_CCI_strength_can_be_already_above100')
    interrupted = [synthetic_bar(base + i * STEP) for i in range(103) if i != 50]
    interrupted[69] = synthetic_bar(interrupted[69]['ts'], canonical=False)
    a = annotate(interrupted)
    check(a[50]['canonical_run'] == 1 and a[49]['canonical_run'] == 50, 'missing_anchor_resets_segment')
    check(a[69]['canonical_run'] == 0 and a[70]['canonical_run'] == 1,
          'noncanonical_row_and_next_row_segment_reset')
    check(all(a[69][k] is None for k in ['tp', 'atr14', 'aroon_up', 'prior_both_low', 'transition',
                                       'cci_gate', 'exit_level', 'current_high_ties_previous']),
          'noncanonical_indicator_predicates_unavailable_not_false')
    check(flat_tp[-1]['canonical_run'] == 101, 'zero_volume_does_not_reset')
    one_range_zero = [synthetic_bar(base + i * STEP) for i in range(101)]
    one_range_zero[25] = synthetic_bar(base + 25 * STEP, h='100', l='100')
    check(annotate(one_range_zero)[-1]['canonical_run'] == 101, 'genuine_zero_range_does_not_reset')
    micro_fields = synthetic_bar(base)['source_fields'][:]
    micro_fields[0] = str(base * 1000000)
    micro_fields[6] = str((base + STEP) * 1000000 - 1)
    micro = decode_row(micro_fields, '2024-01')
    check(micro['canonical'] and micro['timestamp_scale'] == 1000000 and micro['source_fields'] == micro_fields,
          'source_microsecond_exact_close_minus_one_preserved')
    micro_fields[6] = str((base + STEP) * 1000000 - 2)
    check(not decode_row(micro_fields, '2024-01')['canonical'], 'no_rounding_close_label_canonical_check')
    for model in ('primary', 'no_cci'):
        run = run_account(flat_tp, model, 'base', 'x', base + STEP, base + 101 * STEP)
        check(run['metrics']['trades'] == 0 and run['metrics']['return_pct'] == 0 and
              run['metrics']['profit_factor'] is None and run['metrics']['mean_r'] is None and
              run['metrics']['drawdown_pct'] == 0, 'zero_trade_and_same_common_mask_' + model)
    # All following tests run complete funded accounts with event queues and sale reserves.
    flags = {0: dict(eligible=True, transition=True)}
    b = execution_bars(2, updates=flags)
    run = run_account(b, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
    trade = run['trades'][0]
    check(len(run['trades']) == 1 and trade['entry_ts'] == base + STEP and trade['signal_ts'] == base + STEP,
          'preperiod_close_can_enter_exact_period_start')
    check(trade['signal_cci'] == 200 and trade['reason'] == 'period_end',
          'strength_gate_not_prior_CCI_crossing')
    check(trade['cash_before'] + trade['pnl'] == run['metrics']['end_cash'],
          'complete_reserved_cash_sale_reconciliation')
    check(trade['entry'] == D('100.05') and trade['exit'] == D('99.9500') and
          trade['fees'] == trade['qty'] * (trade['entry'] + trade['exit']) * D('.001'),
          'multiplicative_fills_actual_two_sided_fees')
    check(trade['pnl'] < 0 and run['metrics']['fees'] > 0 and run['metrics']['modeled_slippage'] > 0,
          'unmoved_quote_costs_reduce_cash_once')
    check(trade['risk_cash'] == trade['qty'] * trade['unit_loss'] and
          trade['net_r'] == trade['pnl'] / trade['risk_cash'], 'planned_R_denominator_frozen')
    check(run['metrics']['turnover_usdt'] == trade['qty'] * (trade['entry'] + trade['exit']) and
          run['metrics']['turnover'] == run['metrics']['turnover_usdt'] / 10000,
          'gross_turnover_USDT_and_capital_multiple_distinct')
    capped = execution_bars(2, updates={0: dict(eligible=True, transition=True, atr14=D('.1')),
                                       1: dict(l='99.9')})
    caprun = run_account(capped, 'primary', 'zero', 'x', base + STEP, base + 2 * STEP)
    ct = caprun['trades'][0]
    check(ct['cash_capped'] and ct['qty'] == 100 and ct['risk_cash'] == 20,
          'cash_cap_reduces_risk_without_borrowing')
    check(ct['pnl_sign'] == 0 and caprun['metrics']['zero_trades'] == 1 and
          caprun['metrics']['profit_factor'] is None and caprun['metrics']['mean_r'] == 0,
          'exact_zero_net_trade_no_epsilon_PF_null')
    zero_fee_sign = execution_bars(2, updates={
        0: dict(eligible=True, transition=True, atr14=D(1000)),
        1: dict(o='1997001', h='2004000', l='1997000', c='2003001')})
    zrun = run_account(zero_fee_sign, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
    check(zrun['trades'][0]['pnl_sign'] == 0 and zrun['trades'][0]['pnl'] == 0 and
          zrun['metrics']['fees'] > 0 and zrun['metrics']['end_cash'] == 10000,
          'exact_source_fraction_cost_breakeven_not_binary_sign')
    missing = execution_bars(4, updates=flags)
    missing = [b for i, b in enumerate(missing) if i != 1]
    mr = run_account(missing, 'primary', 'base', 'x', base + STEP, base + 4 * STEP)
    check(mr['metrics']['canceled_missing_entry'] == 1 and not mr['trades'],
          'missing_exact_next_open_cancels_never_defers')
    for atr, label in [(D('.001'), 'already_breached'), (D(100), 'nonpositive')]:
        bad = execution_bars(2, updates={0: dict(eligible=True, transition=True, atr14=atr)})
        br = run_account(bad, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
        check(br['metrics']['rejected_entry'] == 1 and not br['trades'] and
              br['metrics']['fees'] == 0 and br['metrics']['end_cash'] == 10000,
              'whole_entry_rejection_' + label)
    nc = execution_bars(2, updates={0: dict(eligible=True, transition=True), 1: dict(canonical=False)})
    nr = run_account(nc, 'primary', 'base', 'x', base + STEP, base + 4 * STEP)
    check(nr['metrics']['trades'] == 1 and nr['trades'][0]['touches_noncanonical'] and
          nr['trades'][0]['partial_close_proxy'] and nr['trades'][0]['early_terminal_proxy'],
          'entry_open_not_censored_by_future_noncanonical_close_nominal_proxy')
    aging = execution_bars(5, updates={0: dict(eligible=True, transition=True),
                                     1: dict(exit_level=True), 3: dict(exit_level=None, canonical=False)})
    aging = [b for i, b in enumerate(aging) if i != 2]
    ar = run_account(aging, 'primary', 'base', 'x', base + STEP, base + 5 * STEP)
    at = ar['trades'][0]
    check(at['reason'] == 'aroon_exit' and at['exit_bar_ts'] == base + 3 * STEP and
          at['delayed_aroon_exit'] and at['crosses_gap'] and at['touches_noncanonical'],
          'persistent_aging_exit_survives_missing_open_undefined_later_state')
    aging_gap = [dict(b) for b in aging]
    row = next(i for i, b in enumerate(aging_gap) if b['ts'] == base + 3 * STEP)
    changed = execution_bars(4, updates={3: dict(o='95', h='96', l='94', c='95', canonical=False)})[3]
    aging_gap[row] = changed
    gr = run_account(aging_gap, 'primary', 'base', 'x', base + STEP, base + 5 * STEP)
    check(gr['trades'][0]['reason'] == 'stop_gap' and not gr['trades'][0]['delayed_aroon_exit'],
          'opening_stop_gap_beats_persistent_aging_exit')
    check(ar['metrics']['exposure_pct'] == D(200) / 3,
          'observed_exposure_includes_open_exit_interval')
    end_aging = execution_bars(3, updates={0: dict(eligible=True, transition=True),
                                         1: dict(exit_level=True), 2: dict(o='1000', h='1001', l='999', c='1000')})
    er = run_account(end_aging, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
    check(er['trades'][0]['reason'] == 'period_end' and er['trades'][0]['exit_ref'] == 100 and
          er['trades'][0]['exit_event_ts'] == base + 2 * STEP,
          'period_end_close_precedes_queued_open_at_or_after_end')
    timed = execution_bars(32, updates=flags)
    tr = run_account(timed, 'primary', 'base', 'x', base + STEP, base + 32 * STEP)
    check(tr['trades'][0]['reason'] == 'time' and tr['trades'][0]['exit_bar_ts'] == base + 30 * STEP and
          tr['trades'][0]['exit_event_ts'] == base + 31 * STEP,
          'time_deadline_is30_scheduled_intervals_entry_is1')
    missed = [b for i, b in enumerate(timed) if i != 30]
    tm = run_account(missed, 'primary', 'base', 'x', base + STEP, base + 32 * STEP)
    check(tm['trades'][0]['reason'] == 'time_delayed' and tm['trades'][0]['exit_bar_ts'] == base + 31 * STEP,
          'missing30th_interval_exits_first_subsequent_open')
    queued_time = [dict(b) for b in missed]
    queued_time[29]['exit_level'] = True
    qt = run_account(queued_time, 'primary', 'base', 'x', base + STEP, base + 32 * STEP)
    check(qt['trades'][0]['reason'] == 'aroon_exit', 'queued_aging_precedes_missed_time_at_same_open')
    stop30 = execution_bars(32, updates={0: dict(eligible=True, transition=True),
                                       30: dict(l='97')})
    st = run_account(stop30, 'primary', 'base', 'x', base + STEP, base + 32 * STEP)
    check(st['trades'][0]['reason'] == 'stop' and st['trades'][0]['net_r'] == -1 and
          st['trades'][0]['exit_precision'] == 'within_4h', 'intrabar_stop_precedes30th_close_and_R_exact_minus1')
    after_stop = execution_bars(3, updates={0: dict(eligible=True, transition=True),
                                          1: dict(l='97', eligible=True, transition=True),
                                          2: dict(h='106', c='105')})
    re = run_account(after_stop, 'primary', 'base', 'x', base + STEP, base + 3 * STEP)
    check(len(re['trades']) == 2 and re['trades'][1]['entry_ts'] == base + 2 * STEP,
          'intrabar_exit_allows_fresh_completed_close_next_open')
    check(abs(re['trades'][0]['pnl'] + 100) < D('1e-40') and re['trades'][1]['pnl'] > 0 and
          re['metrics']['wins'] == re['metrics']['losses'] == 1 and
          re['metrics']['profit_factor'] == re['trades'][1]['pnl'] / 100 and
          re['metrics']['end_cash'] == 9900 + re['trades'][1]['pnl'],
          'complete_two_trade_profit_factor_costs_and_cash_compounding')
    open_exit = execution_bars(4, updates={0: dict(eligible=True, transition=True),
                                         1: dict(exit_level=True),
                                         2: dict(eligible=True, transition=True)})
    ore = run_account(open_exit, 'primary', 'base', 'x', base + STEP, base + 4 * STEP)
    check(len(ore['trades']) == 2 and ore['trades'][0]['exit_bar_ts'] == base + 2 * STEP and
          ore['trades'][1]['entry_ts'] == base + 3 * STEP,
          'opening_exit_cannot_reopen_until_a_new_completed_signal')
    final_candidate = execution_bars(2, updates={1: dict(eligible=True, transition=True)})
    fc = run_account(final_candidate, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
    check(fc['candidates'][0]['action'] == 'outside_period' and not fc['trades'],
          'final_available_end_candidate_recorded_not_entered')
    held_candidate = execution_bars(4, updates={0: dict(eligible=True, transition=True),
                                               1: dict(eligible=True, transition=True, cci_gate=False),
                                               2: dict(exit_level=True)})
    hc = run_account(held_candidate, 'primary', 'base', 'x', base + STEP, base + 4 * STEP)
    check(hc['candidates'][1]['action'] == 'held' and not hc['candidates'][1]['cci_gate'],
          'candidate_gate_and_held_disposition_separate')
    rejected_filter = execution_bars(2, updates={0: dict(eligible=True, transition=True, cci_gate=False)})
    fr = run_account(rejected_filter, 'primary', 'base', 'x', base + STEP, base + 2 * STEP)
    cr = run_account(rejected_filter, 'no_cci', 'base', 'x', base + STEP, base + 2 * STEP)
    check(fr['candidates'][0]['action'] == 'filter_rejected' and not fr['trades'] and len(cr['trades']) == 1,
          'control_drops_only_current_strength_threshold')
    year_base = iso_time('2024-01-01T00:00:00Z') - 2 * STEP
    ybars = execution_bars(3, base=year_base, updates={0: dict(eligible=True, transition=True),
                                                    2: dict(h='111', c='110')})
    yr = run_account(ybars, 'primary', 'base', 'x', year_base + STEP, year_base + 3 * STEP)
    check([x['year'] for x in yr['annual']] == [2023, 2024] and
          yr['equity'][0]['ts'] == iso_time('2024-01-01T00:00:00Z'),
          'annual_membership_by_opening_year_not_available_close_year')
    compound = (1 + yr['annual'][0]['return_pct'] / 100) * (1 + yr['annual'][1]['return_pct'] / 100)
    check(abs(compound - (1 + yr['metrics']['return_pct'] / 100)) < D('1e-45'),
          'annual_marked_returns_compound_to_funded_account')
    bh = buy_hold(ybars, 'x', year_base + STEP, year_base + 3 * STEP)
    check(abs(bh['qty'] * bh['entry'] * D('1.001') - 10000) < D('1e-40') and bh['metrics']['exposure_pct'] == 100,
          'benchmark_separate_fully_cash_funded_entry_with_fee')
    check(bh['equity'][-1]['equity'] == bh['metrics']['end_cash'] and
          bh['entry_fee'] + bh['exit_fee'] == bh['fees'], 'benchmark_sale_fees_and_terminal_equity_reconcile')
    absent = buy_hold([], 'x', base, base + STEP)
    check(not absent['available'] and absent['metrics']['return_pct'] == 0 and not absent['equity'],
          'empty_benchmark_price_path_flagged_unavailable')
    zero_runs = {'primary_base_early': {'trades': []}, 'primary_base_later': {'trades': []}}
    check(all(not x['available'] for x in gallery(ybars, zero_runs)), 'empty_gallery_no_attractive_substitute')
    t0 = dict(signal_bar_ts=ybars[0]['ts'], exit_bar_ts=ybars[1]['ts'], pnl_sign=0)
    t1 = dict(signal_bar_ts=ybars[1]['ts'], exit_bar_ts=ybars[2]['ts'], pnl_sign=-1)
    g = gallery(ybars, {'primary_base_early': {'trades': []},
                       'primary_base_later': {'trades': [t0, t1]}})
    check(g[2]['selection_kind'] == 'next_later' and g[2]['trade'] == t1,
          'zero_first_later_has_no_opposite_falls_to_next_chronological')
    t0p = dict(t0, pnl_sign=1)
    g = gallery(ybars, {'primary_base_early': {'trades': []},
                       'primary_base_later': {'trades': [t0p, dict(t1, pnl_sign=1), t1]}})
    check(g[2]['selection_kind'] == 'opposite_sign' and g[2]['trade'] == t1,
          'gallery_first_strict_opposite_net_sign_not_best_trade')
    return dict(status='passed', assertions=len(results), tests=results,
                historical_price_rows_used=False, primary_code_or_results_used=False)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--protocol', type=Path, required=True)
    parser.add_argument('--manifest', type=Path)
    parser.add_argument('--raw', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    manifest_path = args.manifest or args.protocol.with_name('source-manifest.json')
    directory = args.output.resolve().parent
    lock = lock_code(directory, args.protocol.resolve(), manifest_path.resolve())
    tests = boundary_tests()
    write_json(directory / 'boundary-tests.json', tests)
    print(json.dumps({'stage': 'synthetic_boundary_tests_complete', 'assertions': tests['assertions']}), flush=True)
    protocol, manifest = read_json(args.protocol), read_json(manifest_path)
    source, quality = load_originals(args.raw, manifest, protocol)
    bars = annotate(source)
    quality.update(eligible_rows=sum(b['eligible'] for b in bars),
                   transition_rows=sum(b['transition'] is True for b in bars),
                   eligible_transition_rows=sum(b['eligible'] and b['transition'] is True for b in bars),
                   cci_passed_transitions=sum(b['eligible'] and b['transition'] is True and b['cci_gate'] is True for b in bars))
    periods = {key: tuple(map(iso_time, values)) for key, values in protocol['periods'].items()}
    runs = {}
    for model in ('primary', 'no_cci'):
        for cost in ('base', 'zero', 'higher'):
            for period, (start, end) in periods.items():
                key = model + '_' + cost + '_' + period
                runs[key] = run_account(bars, model, cost, period, start, end,
                                        D(str(protocol['initial_cash'])))
    benchmarks = {period: buy_hold(bars, period, start, end,
                                   D(str(protocol['initial_cash'])))
                  for period, (start, end) in periods.items()}
    result = dict(protocol=protocol, protocol_sha256=lock['protocol_sha256'],
                  manifest=manifest, manifest_sha256=lock['manifest_sha256'],
                  data_quality=quality, bars=bars, runs=runs, buy_hold=benchmarks,
                  examples=gallery(bars, runs))
    raw_json = json_bytes(result)
    output_bytes = gzip.compress(raw_json, compresslevel=9, mtime=0)
    if args.output.exists():
        raise FileExistsError('Refusing to overwrite an independently locked result')
    args.output.write_bytes(output_bytes)
    # The extra proof keeps all Decimal50 account and ATR values, before float serialization.
    decimal_json = json_bytes(result, precise=True)
    decimal_path = directory / 'independent-decimal50-result.json.gz'
    with decimal_path.open('xb') as stream:
        stream.write(gzip.compress(decimal_json, compresslevel=9, mtime=0))
    result_lock = dict(status='independently_rebuilt_and_locked_before_primary_access',
                       at_utc=now(), code_sha256=lock['code_sha256'],
                       protocol_sha256=lock['protocol_sha256'], manifest_sha256=lock['manifest_sha256'],
                       result_sha256=digest(output_bytes), decompressed_result_sha256=digest(raw_json),
                       decimal50_result_sha256=digest(decimal_path.read_bytes()),
                       decimal50_decompressed_sha256=digest(decimal_json),
                       source_fingerprint_sha256=quality['source_fingerprint_sha256'],
                       source_rows=len(bars), source_files=len(manifest['files']), account_runs=len(runs),
                       buy_hold_accounts=len(benchmarks), trades=sum(len(r['trades']) for r in runs.values()),
                       equity_rows=sum(len(r['equity']) for r in runs.values()),
                       candidate_rows=sum(len(r['candidates']) for r in runs.values()),
                       annual_rows=sum(len(r['annual']) for r in runs.values()),
                       benchmark_equity_rows=sum(len(r['equity']) for r in benchmarks.values()),
                       synthetic_assertions=tests['assertions'], primary_code_or_results_read=False,
                       comparison_started=False)
    with (directory / 'independent-result-lock.json').open('x') as stream:
        json.dump(result_lock, stream, indent=2)
        stream.write('\n')
    print(json.dumps(result_lock, indent=2), flush=True)


if __name__ == '__main__':
    main()
