#!/usr/bin/env python3
"""Frozen EURJPY CCI20 zero-line continuation / prior-information SAR trail.

Requires NumPy for original integer quote arrays. Indicators and executable price
references are exact Fractions; only quantities and JPY account projections are
binary64. No network, counterpart implementation or precomputed price series.
"""
import argparse
import bisect
import datetime as dt
from fractions import Fraction as F
import gzip
import hashlib
import io
import json
import math
from pathlib import Path
import re
import statistics
import sys
import zipfile
from zoneinfo import ZoneInfo

import numpy as np

sys.set_int_max_str_digits(0)
UTC = dt.timezone.utc
NY = ZoneInfo('America/New_York')
STEP = 14400
SCALE = 1000000
PROTOCOL_SHA = '6885a4a82aeba1289e333c9526c4651e80f2370e90078f5a66559e7796ada8aa'
MANIFEST_SHA = '1d7ad30f49b21ec6a3fbf92b07d4460770b4737e02c125888c1a8e4f72b35732'


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


def pair(x):
    return None if x is None else [str(x.numerator), str(x.denominator)]


def sign(x):
    return (x > 0) - (x < 0)


def digest(p):
    h = hashlib.sha256()
    with Path(p).open('rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


def price_int(text):
    if not re.fullmatch(r'[0-9]+(?:\.[0-9]{1,6})?', text):
        raise ValueError('Invalid source price precision or syntax')
    a, _, b = text.partition('.')
    return int(a) * SCALE + int((b + '000000')[:6])


def read_source(folder, protocol, manifest):
    expected = protocol['source_selection']['files']
    entries = {x['file']: x for x in manifest['files']}
    if set(expected) != set(entries) or len(expected) != 7:
        raise ValueError('Frozen selection/manifest differ')
    chunks, duplicates, backwards = [], [], []
    raw_count = 0
    days = {}
    for name in expected:
        p = Path(folder) / name
        meta = entries[name]
        if p.stat().st_size != meta['bytes'] or digest(p) != meta['sha256']:
            raise ValueError('Original archive integrity: ' + name)
        rows = []
        seen = {}
        previous = None
        with zipfile.ZipFile(p) as z:
            if z.testzip() is not None:
                raise ValueError('Original ZIP CRC failure')
            actual = {m.filename: m for m in z.infolist()}
            if set(actual) != {m['name'] for m in meta['members']}:
                raise ValueError('Unexpected archive members')
            for m in meta['members']:
                a = actual[m['name']]
                if a.file_size != m['bytes'] or f'{a.CRC:08x}' != m['crc32'].lower():
                    raise ValueError('Frozen member metadata differs')
            csvs = [n for n in actual if n.lower().endswith('.csv')]
            if len(csvs) != 1 or not re.fullmatch(r'DAT_ASCII_EURJPY_M1_\d{4}\.csv', csvs[0]):
                raise ValueError('Unexpected CSV identity')
            with z.open(csvs[0]) as f:
                for rn, line in enumerate(f, 1):
                    raw_count += 1
                    fields = line.decode('ascii').rstrip('\r\n').split(';')
                    if len(fields) != 6:
                        raise ValueError('Source CSV must contain six fields')
                    stamp = fields[0]
                    if not re.fullmatch(r'\d{8} \d{6}', stamp):
                        raise ValueError('Invalid source minute label')
                    if previous is not None and stamp < previous:
                        backwards.append(dict(file=name, row=rn, previous_stamp=previous, stamp=stamp))
                    previous = stamp
                    if stamp in seen:
                        prior, first = seen[stamp]
                        if prior != line:
                            raise ValueError('Conflicting duplicate source minute')
                        duplicates.append(dict(file=name, first_row=first, duplicate_row=rn,
                                               source_stamp=stamp, line_sha256=hashlib.sha256(line).hexdigest()))
                        continue
                    seen[stamp] = (line, rn)
                    date, clock = stamp.split(' ')
                    hh, mm, ss = int(clock[:2]), int(clock[2:4]), int(clock[4:])
                    if hh >= 24 or mm >= 60 or ss != 0:
                        raise ValueError('Invalid minute resolution')
                    if date not in days:
                        days[date] = int(dt.datetime(int(date[:4]), int(date[4:6]), int(date[6:]),
                                                    tzinfo=UTC).timestamp()) + 18000
                    t = days[date] + hh * 3600 + mm * 60
                    o, h, l, c = map(price_int, fields[1:5])
                    if not 0 < l <= min(o, c) <= max(o, c) <= h:
                        raise ValueError('Nonpositive/inconsistent original OHLC')
                    rows.append((t, o, h, l, c))
        chunks.append(np.asarray(rows, dtype=np.int64))
        del rows, seen
    a = np.concatenate(chunks)
    del chunks
    a = a[np.argsort(a[:, 0], kind='stable')]
    if np.any(np.diff(a[:, 0]) <= 0):
        raise ValueError('Duplicate UTC source rows across archives')
    warmup = epoch(protocol['warmup_start_utc'])
    end = max(epoch(v[1]) for v in protocol['periods'].values())
    a = a[(a[:, 0] >= warmup) & (a[:, 0] < end)]
    if not len(a):
        raise ValueError('No retained source rows')
    h = hashlib.sha256()
    for off in range(0, len(a), 50000):
        h.update(''.join(';'.join(str(int(v)) for v in row) + '\n'
                         for row in a[off:off + 50000]).encode('ascii'))
    norm = dict(source_files=len(expected), rows=len(a), raw_rows_all_archives=raw_count,
                exact_duplicate_rows_removed=len(duplicates), duplicate_audit=duplicates,
                source_backward_jumps=backwards, normalized_m1_sha256=h.hexdigest(),
                first_ts=int(a[0, 0]), last_ts=int(a[-1, 0]))
    return a, norm


def aggregate(a):
    anchors = (a[:, 0] // STEP) * STEP
    starts = np.r_[0, np.flatnonzero(np.diff(anchors)) + 1]
    ends = np.r_[starts[1:], len(a)]
    highs = np.maximum.reduceat(a[:, 2], starts)
    lows = np.minimum.reduceat(a[:, 3], starts)
    bars = []
    ranges = []
    for k, (i, j) in enumerate(zip(starts, ends)):
        ti = int(anchors[i])
        raw = [int(a[i, 1]), int(highs[k]), int(lows[k]), int(a[j - 1, 4])]
        b = dict(ts=ti, **dict(zip(('open', 'high', 'low', 'close'), (v / SCALE for v in raw))),
                 n=int(j - i), first_ts=int(a[i, 0]), last_ts=int(a[j - 1, 0]),
                 **dict(zip(('source_open_int', 'source_high_int', 'source_low_int', 'source_close_int'), raw)))
        bars.append(b)
        ranges.append((int(i), int(j)))
    return bars, ranges


def sar_step(direction, incoming, ep, af, high, low, prev_high, prev_low, start, step, cap):
    prior_direction, prior_ep, prior_af = direction, ep, af
    reversal = low <= incoming if direction == 1 else high >= incoming
    extended = False
    if reversal:
        direction = -direction
        dot = max(ep, prev_high, high) if direction == -1 else min(ep, prev_low, low)
        ep = low if direction == -1 else high
        af = start
    else:
        dot = incoming
        if (direction == 1 and high > ep) or (direction == -1 and low < ep):
            ep = high if direction == 1 else low
            af = min(af + step, cap)
            extended = True
    raw = dot + af * (ep - dot)
    nxt = min(raw, prev_low, low) if direction == 1 else max(raw, prev_high, high)
    values = dict(incoming_sar=incoming, direction_before=prior_direction,
                  ep_before=prior_ep, af_before=prior_af, sar=dot, direction_after=direction,
                  ep=ep, af=af, reversal=reversal, ep_updated=extended,
                  raw_next=raw, next_sar=nxt, clamp_applied=nxt != raw)
    return values


def indicators(bars, protocol):
    parameters = protocol['sar']['parameters']
    start, step, cap = (F(parameters[k]) for k in ('start', 'step', 'maximum'))
    tr_seed = []
    atr = None
    z_values = []
    prior_cci = None
    incoming = ep = af = direction = None
    private = []
    sar_names = ['incoming_sar', 'direction_before', 'ep_before', 'af_before', 'sar',
                 'direction_after', 'ep', 'af', 'reversal', 'ep_updated', 'raw_next',
                 'next_sar', 'clamp_applied']
    for i, b in enumerate(bars):
        h, l, c = (b['source_' + k + '_int'] for k in ('high', 'low', 'close'))
        prev_close = bars[i - 1]['source_close_int'] if i else c
        tr = max(h - l, abs(h - prev_close), abs(l - prev_close))
        if i < 14:
            tr_seed.append(tr)
        if i == 13:
            atr = F(sum(tr_seed), 14 * SCALE)
        elif i > 13:
            atr = (13 * atr + F(tr, SCALE)) / 14
        z = h + l + c
        z_values.append(z)
        tp, mean, mad, cci = F(z, 3 * SCALE), None, None, None
        if i >= 19:
            window = z_values[-20:]
            total = sum(window)
            abs_total = sum(abs(20 * v - total) for v in window)
            mean, mad = F(total, 60 * SCALE), F(abs_total, 1200 * SCALE)
            if abs_total:
                cci = F(4000 * (20 * z - total), 3 * abs_total)
        states = {k: None for k in sar_names}
        exact = {}
        if i:
            H, L = F(h, SCALE), F(l, SCALE)
            if i == 1:
                H0, L0 = F(bars[0]['source_high_int'], SCALE), F(bars[0]['source_low_int'], SCALE)
                down, up = L0 - L, H - H0
                direction = -1 if down > 0 and down > up else 1
                incoming = L0 if direction == 1 else H0
                ep = H if direction == 1 else L
                af = start
                PH, PL = H, L
            else:
                PH, PL = F(bars[i - 1]['source_high_int'], SCALE), F(bars[i - 1]['source_low_int'], SCALE)
            vals = sar_step(direction, incoming, ep, af, H, L, PH, PL, start, step, cap)
            direction, ep, af, incoming = vals['direction_after'], vals['ep'], vals['af'], vals['next_sar']
            exact = {k: pair(v) for k, v in vals.items() if isinstance(v, F)}
            states = {k: float(v) if isinstance(v, F) else v for k, v in vals.items()}
        full = b['n'] == 240 and b['first_ts'] == b['ts'] and b['last_ts'] == b['ts'] + STEP - 60
        adjacent = bool(i and b['ts'] - bars[i - 1]['ts'] == STEP)
        cross = 0
        if adjacent and cci is not None and prior_cci is not None:
            cross = 1 if prior_cci <= 0 < cci else -1 if prior_cci >= 0 > cci else 0
        eligible = bool(i >= 99 and full and bars[i - 1]['canonical'] and adjacent
                        and atr is not None and atr > 0 and cci is not None and prior_cci is not None
                        and states['direction_after'] is not None and bars[i - 1]['direction_after'] is not None)
        signal = cross if eligible and cross == states['direction_after'] == bars[i - 1]['direction_after'] else 0
        b.update(observed_index=i, canonical=full, warmup_ready=i >= 99,
                 atr14=float(atr) if atr is not None else None, atr_exact=pair(atr),
                 tp=float(tp), mean_tp=float(mean) if mean is not None else None,
                 mad=float(mad) if mad is not None else None,
                 cci=float(cci) if cci is not None else None,
                 cci_num=str(cci.numerator) if cci is not None else None,
                 cci_den=str(cci.denominator) if cci is not None else None,
                 **states, sar_exact=exact, eligible=eligible, cci_cross=cross, signal=int(signal),
                 partial_lookback20=sum(not x['canonical'] for x in bars[max(0, i - 19):i]) + int(not full))
        private.append(dict(cci=cci, next_sar=incoming if i else None,
                            atr=atr if signal else None))
        prior_cci = cci
    return bars, private


def calendar(start, end):
    d = 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)
    roll, units, fridays, sessions = [], [], [], []
    while d <= last:
        t = int(dt.datetime.combine(d, dt.time(17), NY).timestamp())
        if d.weekday() < 5:
            roll.append(t)
            units.append(3 if d.weekday() == 2 else 1)
        if d.weekday() == 4:
            fridays.append(t)
        if d.weekday() == 6:
            sessions.append((t, int(dt.datetime.combine(d + dt.timedelta(days=5), dt.time(17), NY).timestamp())))
        d += dt.timedelta(days=1)
    return dict(roll=np.asarray(roll, dtype=np.int64), units=np.asarray(units, dtype=np.int64),
                prefix=np.r_[0, np.cumsum(units, dtype=np.int64)], fridays=fridays,
                sessions=sessions, session_starts=[s for s, _ in sessions])


def in_session(t, cal):
    i = bisect.bisect_right(cal['session_starts'], t) - 1
    return i >= 0 and t < cal['sessions'][i][1]


def charge_units(cal, entry, event, kind):
    a = int(np.searchsorted(cal['roll'], entry, side='right'))
    b = int(np.searchsorted(cal['roll'], event, side='right' if kind == 'within_1m' else 'left'))
    return int(cal['prefix'][b] - cal['prefix'][a])


def quality(a, bars, cal):
    inside, outside, gaps = [], [], []
    for k in np.flatnonzero(np.diff(a[:, 0]) > 60):
        left, right = int(a[k, 0]), int(a[k + 1, 0])
        missing = np.arange(left + 60, right, 60, dtype=np.int64)
        mask = np.zeros(len(missing), dtype=bool)
        for s, e in cal['sessions']:
            if e <= left:
                continue
            if s >= right:
                break
            mask |= (missing >= s) & (missing < e)
        n = int(mask.sum())
        inside.extend(missing[mask].tolist())
        outside.extend(missing[~mask].tolist())
        gaps.append(dict(left=left, right=right, missing_minutes=len(missing),
                         in_session_unobserved=n, outside_weekly_session=len(missing) - n))
    q = dict(source_files=7, rows=len(bars), source_minute_rows=len(a),
             complete_buckets=sum(b['canonical'] for b in bars),
             partial_buckets=sum(not b['canonical'] for b in bars),
             missing_h4_anchors=sum(max(0, (b['ts'] - bars[i - 1]['ts']) // STEP - 1)
                                    for i, b in enumerate(bars) if i),
             gaps=gaps, gap_count=len(gaps), missing_minutes=len(inside) + len(outside),
             in_session_unobserved_minutes=len(inside), outside_weekly_session_minutes=len(outside))
    return q, np.asarray(inside, dtype=np.int64), np.asarray(outside, dtype=np.int64)


def costs(p, name):
    c, pip = p['costs'][name], F(p['pip_size'])
    return dict(spread=pip * F(c['spread_pips']), slip=pip * F(c['slippage_pips_per_leg']),
                commission=F(c['commission_jpy_per_100000eur_per_leg']) / 100000,
                carry=pip * F(c['carry_pips_per_rollover_unit']))


def first_stop(a, lo, hi, stop, direction, spread):
    """Exact integer floor/ceiling search, with no floating hit omission."""
    if hi <= lo:
        return None
    bid_stop = stop - (spread if direction == -1 else 0)
    scaled = bid_stop * SCALE
    threshold = scaled.numerator // scaled.denominator if direction == 1 else -((-scaled.numerator) // scaled.denominator)
    col = 3 if direction == 1 else 2
    flags = a[lo:hi, col] <= threshold if direction == 1 else a[lo:hi, col] >= threshold
    hits = np.flatnonzero(flags)
    if not len(hits):
        return None
    j = lo + int(hits[0])
    raw_open = F(int(a[j, 1]), SCALE) + (spread if direction == -1 else 0)
    gap = raw_open <= stop if direction == 1 else raw_open >= stop
    return dict(index=j, event_ts=int(a[j, 0]), kind='open' if gap else 'within_1m',
                reference=raw_open if gap else stop, reason='stop_gap' if gap else 'stop',
                deadline=None, deadline_reason=None)


def segment_exit(a, start, boundary, end, stop, direction, cost, time_due, week_due,
                 opposite_due, terminal_index):
    ts = a[:, 0]
    lo, hi = int(np.searchsorted(ts, start)), int(np.searchsorted(ts, min(boundary, end)))
    options = []
    hit = first_stop(a, lo, hi, stop, direction, cost['spread'])
    if hit:
        options.append(((hit['event_ts'], 1 if hit['kind'] == 'open' else 3), hit))
    duties = [(time_due, 1, 'time'), (week_due, 2, 'week_close')]
    if opposite_due is not None:
        duties.append((opposite_due, 0, 'opposite_state'))
    due, _, why = min(duties)
    j = int(np.searchsorted(ts, max(start, due)))
    if j < hi:
        ref = F(int(a[j, 1]), SCALE) + (cost['spread'] if direction == -1 else 0)
        x = dict(index=j, event_ts=int(ts[j]), kind='open', reference=ref,
                 reason=why, deadline=due, deadline_reason=why)
        options.append(((x['event_ts'], 2), x))
    for cutoff, rank, reason in [(time_due, 1, 'time'), (week_due, 2, 'week_close')]:
        if not start <= cutoff <= min(boundary, end):
            continue
        j = int(np.searchsorted(ts, cutoff - 60))
        if lo <= j < hi and int(ts[j]) == cutoff - 60:
            ref = F(int(a[j, 4]), SCALE) + (cost['spread'] if direction == -1 else 0)
            x = dict(index=j, event_ts=cutoff, kind='close', reference=ref,
                     reason=reason, deadline=cutoff, deadline_reason=reason)
            options.append(((cutoff, 0, rank), x))
    terminal_clock = int(ts[terminal_index]) + 60
    if start <= terminal_clock <= min(boundary, end) and terminal_index >= lo:
        ref = F(int(a[terminal_index, 4]), SCALE) + (cost['spread'] if direction == -1 else 0)
        x = dict(index=terminal_index, event_ts=terminal_clock, kind='close', reference=ref,
                 reason='period_end', deadline=end, deadline_reason='period_end')
        # A deterministic time/week close at this clock has its earlier due cutoff;
        # a terminal close supersedes duties that need a future out-of-period open.
        options.append(((terminal_clock, 0, 3), x))
    return min(options, key=lambda x: x[0])[1] if options else None


def lifecycle(bars, private, a, anchors, entry_ts, initial_stop, direction, cost, model, end, cal):
    j = bisect.bisect_left(anchors, entry_ts)
    if j >= len(bars) or anchors[j] != entry_ts:
        raise ValueError('Exact source entry opening lacks H4 aggregate')
    terminal = int(np.searchsorted(a[:, 0], end)) - 1
    time_due = entry_ts + 30 * STEP
    week_due = cal['fridays'][bisect.bisect_right(cal['fridays'], entry_ts)]
    active, start = initial_stop, entry_ts
    opposite_due, opposite_partial = None, False
    updates = []
    for k in range(j, len(bars)):
        b = bars[k]
        if b['ts'] >= end:
            break
        boundary = min(b['ts'] + STEP, end)
        exit_ = segment_exit(a, start, boundary, end, active, direction, cost,
                             time_due, week_due, opposite_due, terminal)
        if exit_:
            return exit_, active, opposite_due, opposite_partial, updates
        if b['direction_after'] == -direction and opposite_due is None:
            opposite_due, opposite_partial = boundary, not b['canonical']
        if (model == 'primary' and b['direction_after'] == direction and opposite_due is None
                and boundary < time_due and boundary < week_due and boundary < end):
            nxt = private[k]['next_sar']
            proposal = nxt + (cost['spread'] if direction == -1 else 0)
            new = max(active, proposal) if direction == 1 else min(active, proposal)
            updates.append(dict(bar_ts=b['ts'], decision_ts=boundary, activation_ts=boundary,
                                previous_stop=float(active), previous_stop_exact=pair(active),
                                next_sar=float(nxt), next_sar_exact=pair(nxt),
                                proposal_stop=float(proposal), proposal_stop_exact=pair(proposal),
                                new_stop=float(new), new_stop_exact=pair(new), tightened=new != active,
                                partial_source=not b['canonical'], quote_side='Bid' if direction == 1 else 'modeled Ask'))
            active = new
        start = boundary
    raise ValueError('Position did not reach an allowed in-period liquidation')


def marks(bars, trades, refs, cost, begin, end, cal, initial):
    points, realized, peak, k, occ_index = [], initial, initial, 0, 0
    for b in bars:
        if not begin <= b['ts'] < end:
            continue
        cutoff = min(b['ts'] + STEP, end)
        while k < len(trades) and (trades[k]['exit_event_ts'] < cutoff or
                trades[k]['exit_event_ts'] == cutoff and trades[k]['exit_event_kind'] == 'close'):
            realized = trades[k]['cash_after']
            k += 1
        value = actual_cash = realized
        if k < len(trades) and trades[k]['entry_ts'] < cutoff:
            t, ref = trades[k], refs[k]
            u = charge_units(cal, t['entry_ts'], cutoff, 'close')
            x = F(b['source_close_int'], SCALE) + (cost['spread'] if t['direction'] == -1 else 0) - t['direction'] * cost['slip']
            unit = t['direction'] * (x - ref['entry']) - 2 * cost['commission'] - cost['carry'] * u
            value = t['preentry_equity'] + t['quantity'] * float(unit)
            actual_cash = t['preentry_equity'] - t['quantity'] * float(cost['commission']) - t['quantity'] * float(cost['carry']) * u
        while occ_index < len(trades) and (trades[occ_index]['exit_event_ts'] < b['ts'] or
                trades[occ_index]['exit_event_ts'] == b['ts'] and trades[occ_index]['exit_event_kind'] == 'close'):
            occ_index += 1
        occupied = occ_index < len(trades) and trades[occ_index]['entry_ts'] < cutoff
        if not math.isfinite(value) or not math.isfinite(actual_cash):
            raise ValueError('Nonfinite account mark')
        peak = max(peak, value)
        points.append(dict(ts=cutoff, bar_ts=b['ts'], equity=value, cash=actual_cash,
                           drawdown_pct=100 * (peak - value) / peak, occupied=bool(occupied)))
    return points


def simulate(bars, private, a, p, model, cost_name, period, cal, missing_inside, missing_outside):
    begin, end = map(epoch, p['periods'][period])
    cost = costs(p, cost_name)
    initial = float(p['account']['initial_cash'])
    cash, trades, refs, candidates = initial, [], [], []
    anchors = [b['ts'] for b in bars]
    ts = a[:, 0]
    for i, b in enumerate(bars):
        t, direction = b['ts'] + STEP, b['signal']
        if not begin <= t < end or not direction:
            continue
        idx = int(np.searchsorted(ts, t))
        available = idx < len(a) and int(ts[idx]) == t
        session = in_session(t, cal)
        prior = bars[i - 1]
        rec = dict(signal_ts=b['ts'], decision_ts=t, direction=direction,
                   side='long' if direction == 1 else 'short', cci=b['cci'], cci_num=b['cci_num'], cci_den=b['cci_den'],
                   prev_cci=prior['cci'], prev_cci_num=prior['cci_num'], prev_cci_den=prior['cci_den'],
                   sar=b['sar'], next_sar=b['next_sar'], af=b['af'], previous_state=prior['direction_after'],
                   current_state=b['direction_after'], partial_lookback_buckets=b['partial_lookback20'],
                   entry_quote_available=bool(available), weekly_session_open=bool(session))
        last = trades[-1] if trades else None
        occupied = last is not None and (t < last['exit_event_ts'] or
                     t == last['exit_event_ts'] and last['exit_event_kind'] != 'close')
        if not session:
            action = 'outside_weekly_session'
        elif occupied:
            action = 'occupied'
        elif cash <= 0:
            action = 'insolvent'
        elif not available:
            action = 'missing_entry_open'
        else:
            if not math.isfinite(cash):
                raise ValueError('Nonfinite account cash')
            bid = F(int(a[idx, 1]), SCALE)
            entry = bid + (cost['spread'] if direction == 1 else 0) + direction * cost['slip']
            atr = private[i]['atr']
            stop = entry - direction * 2 * atr
            lunit = 2 * atr + cost['slip'] + 2 * cost['commission']
            if entry <= 0:
                action = 'invalid_entry_price'
            elif stop <= 0 or lunit <= 0 or (stop >= bid if direction == 1 else stop <= bid + cost['spread']):
                action = 'invalid_stop'
            else:
                risk_q = float(p['account']['risk_fraction']) * cash / float(lunit)
                cap_q = cash / float(abs(entry) + cost['commission'])
                q = min(risk_q, cap_q)
                if not math.isfinite(q) or q <= 0:
                    raise ValueError('Nonpositive/nonfinite projected quantity')
                x, final_stop, opposite_due, opposite_partial, updates = lifecycle(
                    bars, private, a, anchors, t, stop, direction, cost, model, end, cal)
                exit_ref = x['reference']
                fill = exit_ref - direction * cost['slip']
                u = charge_units(cal, t, x['event_ts'], x['kind'])
                net = direction * (fill - entry) - 2 * cost['commission'] - cost['carry'] * u
                pnl = q * float(net)
                after = cash + pnl
                if not math.isfinite(after):
                    raise ValueError('Nonfinite realized cash')
                stop_bid = final_stop - (cost['spread'] if direction == -1 else 0)
                exit_anchor = int(a[x['index'], 0]) // STEP * STEP
                left_h4, right_h4 = bisect.bisect_left(anchors, t), bisect.bisect_right(anchors, exit_anchor)
                side = 'right' if x['kind'] == 'within_1m' else 'left'
                missing = int(np.searchsorted(missing_inside, x['event_ts'], side=side) - np.searchsorted(missing_inside, t, side='right'))
                outside = int(np.searchsorted(missing_outside, x['event_ts'], side=side) - np.searchsorted(missing_outside, t, side='right'))
                planned_r = q * float(lunit)
                trade = dict(number=len(trades) + 1, model=model, cost=cost_name, period=period,
                    side='long' if direction == 1 else 'short', direction=direction, signal_bar_ts=b['ts'],
                    decision_ts=t, entry_ts=t, exit_event_ts=x['event_ts'], exit_event_kind=x['kind'],
                    source_exit_minute_ts=int(a[x['index'], 0]), exit_bar_ts=exit_anchor,
                    entry_ref=float(bid), entry=float(entry), exit_ref=float(exit_ref),
                    exit_bid_ref=float(exit_ref - (cost['spread'] if direction == -1 else 0)), exit=float(fill),
                    stop_initial=float(stop), stop_initial_bid=float(stop - (cost['spread'] if direction == -1 else 0)),
                    stop_final=float(final_stop), stop_final_bid=float(stop_bid),
                    stop_initial_exact=pair(stop), stop_final_exact=pair(final_stop),
                    signal_atr=b['atr14'], signal_cci=b['cci'], signal_prev_cci=prior['cci'],
                    signal_sar=b['sar'], signal_next_sar=b['next_sar'], signal_af=b['af'],
                    signal_direction_before=b['direction_before'], signal_direction_after=b['direction_after'],
                    quantity=q, preentry_equity=cash, lunit=float(lunit), risk_cash=planned_r,
                    notional=q * float(abs(entry)),
                    notional_capped=F(p['account']['risk_fraction']) * (abs(entry) + cost['commission']) > lunit,
                    pnl=pnl, pnl_sign=sign(net), net_unit_num=str(net.numerator), net_unit_den=str(net.denominator),
                    net_r=pnl / planned_r, fees=2 * q * float(cost['commission']),
                    financing=q * float(cost['carry']) * u, rollover_units=u, cash_after=after,
                    reason=x['reason'], deadline=x['deadline'], deadline_reason=x['deadline_reason'],
                    opposite_deadline=opposite_due,
                    delayed_exit=x['reason'] in ('opposite_state', 'time', 'week_close') and x['event_ts'] > x['deadline'],
                    early_terminal_proxy=x['reason'] == 'period_end' and x['event_ts'] < end,
                    crosses_gap=missing > 0, missing_open_minutes_crossed=missing,
                    outside_session_missing_minutes=outside, partial_lookback_buckets=b['partial_lookback20'],
                    partial_holding_buckets=sum(not z['canonical'] for z in bars[left_h4:right_h4]),
                    partial_exit_signal=x['reason'] == 'opposite_state' and opposite_partial,
                    partial_trail_updates=sum(z['partial_source'] for z in updates), trail_updates=len(updates),
                    tightenings=sum(z['tightened'] for z in updates), protective_updates=updates,
                    quote_side_exit='Bid' if direction == 1 else 'modeled Ask',
                    entry_ref_exact=pair(bid), entry_exact=pair(entry), exit_ref_exact=pair(exit_ref),
                    exit_exact=pair(fill), lunit_exact=pair(lunit),
                    spread_cost=q * float(cost['spread']), entry_slippage=q * float(cost['slip']),
                    exit_slippage=q * float(cost['slip']), slippage_cost=2 * q * float(cost['slip']),
                    turnover_jpy=q * float(abs(entry) + abs(fill)))
                trades.append(trade)
                refs.append(dict(entry=entry))
                cash = after
                action = 'entry'
        candidates.append(dict(rec, action=action))
    equity = marks(bars, trades, refs, cost, begin, end, cal, initial)
    if equity and abs(equity[-1]['equity'] - cash) > 0.0001:
        raise ValueError('Terminal marked equity differs from final cash')
    positives = [t['pnl'] for t in trades if t['pnl_sign'] > 0]
    negatives = [t['pnl'] for t in trades if t['pnl_sign'] < 0]
    loss = -math.fsum(negatives)
    rs = [t['net_r'] for t in trades]
    turnover = math.fsum(t['quantity'] * (abs(t['entry']) + abs(t['exit'])) for t in trades)
    metrics = dict(return_pct=100 * (cash / initial - 1), end_cash=cash,
        drawdown_pct=max((v['drawdown_pct'] for v in equity), default=0), trades=len(trades),
        wins=sum(t['pnl_sign'] > 0 for t in trades), losses=sum(t['pnl_sign'] < 0 for t in trades),
        breakevens=sum(t['pnl_sign'] == 0 for t in trades),
        profit_factor=math.fsum(positives) / loss if loss else None,
        mean_r=statistics.mean(rs) if rs else None, median_r=statistics.median(rs) if rs else None,
        sum_r=math.fsum(rs), fees=math.fsum(t['fees'] for t in trades),
        financing=math.fsum(t['financing'] for t in trades), rollover_units=sum(t['rollover_units'] for t in trades),
        exposure_pct=100 * sum(v['occupied'] for v in equity) / len(equity) if equity else 0,
        notional_capped=sum(t['notional_capped'] for t in trades),
        canceled_missing_entry=sum(c['action'] == 'missing_entry_open' for c in candidates),
        invalid_stop=sum(c['action'] == 'invalid_stop' for c in candidates),
        gap_trades=sum(t['crosses_gap'] for t in trades), partial_trades=sum(t['partial_holding_buckets'] > 0 for t in trades),
        partial_lookback_trades=sum(t['partial_lookback_buckets'] > 0 for t in trades),
        partial_exit_signal_trades=sum(t['partial_exit_signal'] for t in trades),
        delayed_state_exits=sum(t['reason'] == 'opposite_state' and t['delayed_exit'] for t in trades),
        delayed_time_week_exits=sum(t['reason'] in ('time', 'week_close') and t['delayed_exit'] for t in trades),
        early_terminal_proxies=sum(t['early_terminal_proxy'] for t in trades),
        spread_cost=math.fsum(t['quantity'] * float(cost['spread']) for t in trades),
        slippage_cost=math.fsum(2 * t['quantity'] * float(cost['slip']) for t in trades),
        turnover=turnover / initial, turnover_jpy=turnover,
        long_trades=sum(t['direction'] == 1 for t in trades), short_trades=sum(t['direction'] == -1 for t in trades),
        trail_updates=sum(t['trail_updates'] for t in trades), tightenings=sum(t['tightenings'] for t in trades),
        trades_with_tightening=sum(t['tightenings'] > 0 for t in trades), sample_limited=len(trades) < 30)
    yearly = {}
    for v in equity:
        yearly[dt.datetime.fromtimestamp(v['bar_ts'], UTC).year] = v['equity']
    annual, previous = [], initial
    for year, finish in yearly.items():
        annual.append(dict(year=year, return_pct=100 * (finish / previous - 1) if previous else None,
                           start_equity=previous, end_equity=finish))
        previous = finish
    return dict(model=model, cost=cost_name, period=period, start_ts=begin, end_ts=end,
                metrics=metrics, trades=trades, equity=equity, annual=annual, candidates=candidates)


def gallery(runs, bars, a):
    early, later = runs['primary_base_early']['trades'], runs['primary_base_later']['trades']
    first = later[0] if later else None
    opposite = next((t for t in later[1:] if t['pnl_sign'] * first['pnl_sign'] < 0), None) if first else None
    third = opposite if opposite else later[1] if len(later) > 1 else None
    choices = [('early', early[0] if early else None, 'first_early'),
               ('later', first, 'first_later'), ('opposite', third, 'opposite_sign' if opposite else 'next_later')]
    anchors = [b['ts'] for b in bars]
    out = []
    for tag, trade, selection in choices:
        if trade is None:
            out.append(dict(tag=tag, available=False, selection_kind='unavailable',
                            outcome_conditioned=False, trade=None, bars=[], minute_observations=[]))
            continue
        left = bisect.bisect_left(anchors, trade['signal_bar_ts'])
        right = bisect.bisect_left(anchors, trade['exit_bar_ts'])
        observations = []
        for role, stamp in [('entry', trade['entry_ts']), ('exit', trade['source_exit_minute_ts'])]:
            j = int(np.searchsorted(a[:, 0], stamp))
            if j >= len(a) or int(a[j, 0]) != stamp:
                raise ValueError('Gallery execution source absent')
            v = a[j]
            observations.append(dict(role=role, ts=stamp,
                **dict(zip(('open', 'high', 'low', 'close'), (int(x) / SCALE for x in v[1:]))),
                **dict(zip(('source_open_int', 'source_high_int', 'source_low_int', 'source_close_int'), (int(x) for x in v[1:])))))
        out.append(dict(tag=tag, available=True, selection_kind=selection,
                        outcome_conditioned=tag == 'opposite', trade=trade,
                        bars=bars[max(0, left - 20):right + 4], minute_observations=observations))
    return out


def code_lock(output, protocol_path, manifest_path):
    folder = Path(output).parent
    folder.mkdir(parents=True, exist_ok=True)
    path = Path(__file__).resolve()
    sha = digest(path)
    data = dict(status='locked_before_first_synthetic_or_historical_calculation',
                locked_at_utc=dt.datetime.now(UTC).isoformat(), code_sha256=sha,
                protocol_sha256=digest(protocol_path), manifest_sha256=digest(manifest_path))
    lock = folder / 'primary-code-lock.json'
    if lock.exists():
        old = json.loads(lock.read_text())
        if any(old[k] != data[k] for k in ('code_sha256', 'protocol_sha256', 'manifest_sha256')):
            raise ValueError('Code changed after lock: retain original and use documented correction folder')
    else:
        lock.write_text(json.dumps(data, indent=2) + '\n')
        (folder / ('frozen-primary-' + sha + '.py')).write_bytes(path.read_bytes())
    return sha


def write_result(output, result, code_sha):
    path = Path(output)
    with path.open('wb') as raw:
        with gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=0, compresslevel=6) as zipped:
            with io.TextIOWrapper(zipped, encoding='utf-8') as text:
                json.dump(result, text, ensure_ascii=False, allow_nan=False, separators=(',', ':'))
    h = hashlib.sha256()
    with gzip.open(path, 'rb') as f:
        for block in iter(lambda: f.read(1 << 20), b''):
            h.update(block)
    lock = dict(status='result_locked_before_counterpart_output', locked_at_utc=dt.datetime.now(UTC).isoformat(),
                code_sha256=code_sha, protocol_sha256=PROTOCOL_SHA, manifest_sha256=MANIFEST_SHA,
                result_sha256=h.hexdigest(), gzip_sha256=digest(path), gzip_bytes=path.stat().st_size)
    (path.parent / 'primary-result-lock.json').write_text(json.dumps(lock, indent=2) + '\n')
    return lock


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--raw', required=True)
    parser.add_argument('--protocol', required=True)
    parser.add_argument('--manifest', required=True)
    parser.add_argument('--output', required=True)
    args = parser.parse_args()
    if digest(args.protocol) != PROTOCOL_SHA or digest(args.manifest) != MANIFEST_SHA:
        raise ValueError('Only the frozen protocol and manifest are accepted')
    sha = code_lock(args.output, args.protocol, args.manifest)
    p, m = (json.loads(Path(x).read_text()) for x in (args.protocol, args.manifest))
    a, norm = read_source(args.raw, p, m)
    bars, _ = aggregate(a)
    bars, private = indicators(bars, p)
    cal = calendar(int(a[0, 0]), max(epoch(v[1]) for v in p['periods'].values()))
    dq, missing_inside, missing_outside = quality(a, bars, cal)
    runs = {}
    for model in ['primary', 'no_trail']:
        for cost in ['base', 'zero', 'higher']:
            for period in ['full', 'early', 'later']:
                key = model + '_' + cost + '_' + period
                runs[key] = simulate(bars, private, a, p, model, cost, period, cal, missing_inside, missing_outside)
                print(key, json.dumps(runs[key]['metrics'], separators=(',', ':')), flush=True)
    result = dict(protocol=p, protocol_sha256=PROTOCOL_SHA, manifest=m, manifest_sha256=MANIFEST_SHA,
                  normalization=norm, data_quality=dq, bars=bars, runs=runs,
                  examples=gallery(runs, bars, a),
                  cash_reference={period:dict(initial_cash=p['account']['initial_cash'],
                    end_cash=p['account']['initial_cash'], return_pct=0, drawdown_pct=0) for period in p['periods']})
    lock = write_result(args.output, result, sha)
    print(json.dumps(lock), flush=True)


if __name__ == '__main__':
    main()
