"""PF-002 mechanism hypotheses study, version 1.

Virtual lab - simulated experiment. Deterministic mathematics on three proposed
mechanisms and an ordinary baseline. It decides algebraic identities and benchmark
arithmetic, not detection. No mechanism is shown to exist, no equipment is
qualified, and no physical result follows. Benchmark scores use half-widths from
a different acquisition and are never apparatus qualification.

The estimator functions take observation tuples and declared widths. They never
receive a model name, a coupling or any other generator truth.
"""

from fractions import Fraction
from functools import lru_cache
import hashlib
import json
import math
import os
from pathlib import Path
import platform
import sys

import pf002_mechanism_inputs_v1 as inputs
import pf002_mechanism_protocol_v1 as rules

ROOT = Path(__file__).resolve().parent
ENVIRONMENT = rules.ENVIRONMENT
MAX_EXECUTABLE_BYTES = 268435456
MODES = ("fixture", "deterministic_primary")
MODELS = ("B0", "C1", "C2", "C3")
INTERVENTIONS = ("I1", "I2", "I3", "I4", "I5", "I6", "I7")
FORCE_INTERVENTIONS = ("I1", "I6")
SCOPES = ("S01", "S05")
WIDTH_KINDS = ("complete", "benchmark", "unproved")
DISCRIMINATORS = {"C1": ("I4", "I5"), "C2": ("I2", "I3"), "C3": ("I6", "I7")}
# A declared subset. Fixtures never emit the 36 row record.
FIXTURE_ROWS = (("B0", "I1", "S01"), ("B0", "I7", None), ("C1", "I4", None),
                ("C1", "I5", None), ("C2", "I2", None), ("C2", "I3", None),
                ("C3", "I6", "S01"), ("C3", "I7", None))
POWER_SCAN = (Fraction(1, 4), Fraction(1, 2), Fraction(1))


class OperationalFailure(Exception):
    """A declared limit, input or status check failed. It is never a result."""


parse_protocol = rules.parse_protocol
PROTOCOL = rules.load_protocol()
FREEZE = PROTOCOL["mathematical_freeze"]
ADVERSE = PROTOCOL["adverse_cases"]
PRIMARY = PROTOCOL["primary_record"]
CONSTANTS = FREEZE["constants"]
QUADRATURE = FREEZE["quadrature"]
C_LIGHT = CONSTANTS["c_metres_per_second"]
HBAR = CONSTANTS["h_joule_second"]/(2*math.pi)
ELECTRON = CONSTANTS["e_coulomb"]
MU_0 = CONSTANTS["mu_0_newton_per_ampere_squared"]
LAMBDA = Fraction(str(PROTOCOL["source_scope"]["wavelength_m"]))
APERTURE = Fraction(str(PROTOCOL["source_scope"]["aperture_radius_m"]))
SEPARATION = Fraction(str(PROTOCOL["source_scope"]["separation_m"]))
WAVENUMBER = 2*math.pi/float(LAMBDA)
OMEGA = WAVENUMBER*C_LIGHT
K_W = 2*math.pi*float(APERTURE/LAMBDA)
KAPPA = K_W*K_W/2
K_D = 2*math.pi*float(SEPARATION/LAMBDA)
STROKE = PROTOCOL["frozen_domains"]["R_stroke_metres"]
ELLS = tuple(PROTOCOL["frozen_domains"]["ell_metres"])
LOOP_FREQUENCY = PROTOCOL["frozen_domains"]["f_hertz"]
MARGIN = PROTOCOL["required_margin_newtons"]
HALF_WIDTHS = {"S01": PROTOCOL["retained_scalars"]["B1_S01_half_width_newtons"],
               "S05": PROTOCOL["retained_scalars"]["B1_S05_half_width_newtons"]}
DELTA_S = Fraction(1, 2)


def rows():
    """Seven interventions by four models, plus S05 for the two force routes."""
    result = []
    for model in MODELS:
        for intervention in INTERVENTIONS:
            force = intervention in FORCE_INTERVENTIONS
            result.append((model, intervention, "S01" if force else None))
    for model in MODELS:
        for intervention in FORCE_INTERVENTIONS:
            result.append((model, intervention, "S05"))
    return tuple(result)


# Exact enclosure for Proposition M.

PI_LOW = Fraction(314159265358979, 10**14)
PI_HIGH = Fraction(314159265358980, 10**14)
TAIL = Fraction(1, 2**1000)


def _power_integral(power, kappa_low, kappa_high):
    """Enclose the integral of t**power*exp(-kappa*t) over [0, 1]."""
    factorial = math.factorial(power)
    upper = Fraction(factorial)/kappa_low**(power+1)
    tail = TAIL*factorial*(2/kappa_low)**(power+1)
    return Fraction(factorial)/kappa_high**(power+1)-tail, upper


def _product(a, b):
    out = [Fraction(0)]*(len(a)+len(b)-1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i+j] += x*y
    return out


def _poly_integral(poly, kappa_low, kappa_high):
    low = high = Fraction(0)
    for power, coefficient in enumerate(poly):
        a, b = _power_integral(power, kappa_low, kappa_high)
        low += coefficient*(a if coefficient >= 0 else b)
        high += coefficient*(b if coefficient >= 0 else a)
    return low, high


def _moment(poly, kappa_low, kappa_high):
    """Enclose the integral of u*P(t)*exp(-kappa*t), with P >= 0 on [0, 1]."""
    # 1 - t <= sqrt(1 - t) <= 1 - t/2 on [0, 1].
    low, _ = _poly_integral(_product(poly, [Fraction(1), Fraction(-1)]),
                            kappa_low, kappa_high)
    _, high = _poly_integral(_product(poly, [Fraction(1), Fraction(-1, 2)]),
                             kappa_low, kappa_high)
    return low, high


def winding_enclosure(aperture=APERTURE, separation=SEPARATION, wavelength=LAMBDA,
                      stroke=None):
    """Exact interval proof that Re Z > 0 on the contractible domain D.

    With W = g^2*(1 - n_y^2), the common factor pi/2 is dropped from every moment.
    cos(x) >= 1 - x^2/2 and cos(x) <= 1 - x^2/2 + x^4/24 hold for every real x.
    The bound needs I(k*(d - R)) positive, so that |I| is I.
    """
    stroke = Fraction(str(STROKE)) if stroke is None else stroke
    if aperture <= 0 or separation <= 0 or wavelength <= 0 or stroke < 0:
        raise ValueError("enclosure inputs must be positive")
    ratio = aperture/wavelength
    kappa_low = 2*PI_LOW**2*ratio**2
    kappa_high = 2*PI_HIGH**2*ratio**2
    if kappa_low < 1400:
        # exp(-kappa/2) <= 2**-1000 needs kappa/2 >= 1000*log(2).
        return {"proved": False, "cause": "tail_bound_needs_a_larger_kappa"}
    m0 = _moment([Fraction(2), Fraction(-1)], kappa_low, kappa_high)
    m2 = _moment([Fraction(0), Fraction(1), Fraction(-1, 4)], kappa_low, kappa_high)
    m4 = _moment([Fraction(0), Fraction(0), Fraction(3, 4), Fraction(-1, 8)],
                 kappa_low, kappa_high)
    stroke_phase_high = 2*PI_HIGH*stroke/wavelength
    far_low = 2*PI_LOW*(separation-stroke)/wavelength
    far_high = 2*PI_HIGH*separation/wavelength
    if far_low < 0:
        return {"proved": False, "cause": "stroke_exceeds_separation"}
    near_lower = m0[0]-stroke_phase_high**2*m2[1]/2
    far_upper = m0[1]-far_low**2*m2[0]/2+far_high**4*m4[1]/24
    far_lower = m0[0]-far_high**2*m2[1]/2
    proved = far_lower > 0 and near_lower > far_upper
    return {"proved": proved, "cause": None if proved else "enclosure_does_not_close",
            "near_lower_over_m0": float(near_lower/m0[1]),
            "far_lower_over_m0": float(far_lower/m0[1]),
            "far_upper_over_m0": float(far_upper/m0[0]),
            "margin_over_m0": float((near_lower-far_upper)/m0[1])}


# Retained integrals.

def _simpson(low, high, panels):
    step = (high-low)/panels
    for i in range(panels+1):
        weight = 1 if i in (0, panels) else (4 if i % 2 else 2)
        yield low+i*step, weight*step/3


def _half_plane(panels, phases):
    """Integrate on n_x <= 0, so that the mask edge lies on the boundary."""
    total = cosine = moment = half_sine = y_moment = orth = 0.0
    rings = [0.0]*len(phases)
    azimuths = list(_simpson(0.5*math.pi, 1.5*math.pi, panels))
    for rho, radial in _simpson(0.0, 12.0, panels):
        t = rho*rho/KAPPA
        base = radial*2*rho/KAPPA*(math.sqrt(1-t)/2)*math.exp(-rho*rho)
        root = math.sqrt(t)
        for alpha, angular in azimuths:
            nx = root*math.cos(alpha)
            ny = root*math.sin(alpha)
            envelope = base*angular
            w = envelope*(1-ny*ny)
            sine = math.sin(K_D*nx)
            total += w
            cosine += w*math.cos(K_D*nx)
            moment += w*nx*sine
            half_sine += w*sine
            y_moment += envelope*nx*ny*ny*sine
            orth += envelope*(2-nx*nx-ny*ny)
            for i, phase in enumerate(phases):
                rings[i] += w*math.cos(phase*nx)
    return {"m0": 2*total, "cosine": 2*cosine, "moment": 2*moment,
            "half_sine": half_sine, "y_moment": 2*y_moment, "orth": 2*orth,
            "rings": [2*value for value in rings]}


@lru_cache(maxsize=1)
def retained():
    """The retained field's integrals, refused unless the two grids agree."""
    tolerance = QUADRATURE["retained_relative_tolerance"]
    phases = (0.0, WAVENUMBER*STROKE, K_D, K_D-WAVENUMBER*STROKE)
    coarse, fine = (_half_plane(panels, phases)
                    for panels in QUADRATURE["retained_panels"])
    flat = [(coarse[key], fine[key]) for key in ("m0", "cosine", "moment", "half_sine",
                                                 "y_moment", "orth")]
    flat += list(zip(coarse["rings"], fine["rings"]))
    for a, b in flat:
        if abs(a-b) > tolerance*abs(b):
            raise OperationalFailure("retained integrals did not converge")
    m0 = fine["m0"]
    overlap = fine["cosine"]/m0
    fraction = 1/(1+abs(overlap))
    n_hat = abs(fine["moment"])/m0
    f_plus = 0.5+abs(fine["half_sine"])/m0
    return {"C": overlap, "P0": fraction, "n_hat": n_hat, "m0": m0,
            "F_hat": fraction*n_hat/C_LIGHT, "f_plus": f_plus, "f_minus": 1-f_plus,
            "D_f": 2*f_plus-1, "fy_contrast_at_1_W": 4*abs(fine["y_moment"])/fine["orth"]/C_LIGHT,
            "I_near": (fine["rings"][0], fine["rings"][1]),
            "I_far": (fine["rings"][2], fine["rings"][3])}


# Exact loop mathematics. Time runs over one period, so T = 1.

ORIENTATIONS = {1: Fraction(1, 4), -1: Fraction(-1, 4)}
RAMP = Fraction(1, 16)
MAX_SKEW = Fraction(1, 32)


def wave(t):
    t = Fraction(t) % 1
    if t < RAMP:
        return -1+2*t/RAMP
    if t < Fraction(1, 2):
        return Fraction(1)
    if t < Fraction(1, 2)+RAMP:
        return 1-2*(t-Fraction(1, 2))/RAMP
    return Fraction(-1)


def wave_rate(t):
    """Rate inside an interval. Callers evaluate it away from a breakpoint."""
    t = Fraction(t) % 1
    if t < RAMP:
        return 2/RAMP
    if t < Fraction(1, 2):
        return Fraction(0)
    if t < Fraction(1, 2)+RAMP:
        return -2/RAMP
    return Fraction(0)


def _break_times(shifts):
    points = {Fraction(0), Fraction(1)}
    for shift in shifts:
        for corner in (Fraction(0), RAMP, Fraction(1, 2), Fraction(1, 2)+RAMP):
            points.add((corner+shift) % 1)
    return sorted(points)


def _check_orientation(orientation):
    if orientation not in ORIENTATIONS:
        raise ValueError("orientation is +1 or -1")
    return ORIENTATIONS[orientation]


def signals(orientation, skew=Fraction(0)):
    """nu and s, with s lagging nu by T/4 at orientation +1."""
    shift = _check_orientation(orientation)
    if abs(skew) > MAX_SKEW:
        raise ValueError("skew exceeds its frozen limit")
    nu = (lambda t: wave(t-skew), lambda t: wave_rate(t-skew))
    s = (lambda t: Fraction(3, 4)+wave(t-shift)/4, lambda t: wave_rate(t-shift)/4)
    return nu, s, _break_times((skew, shift))


def loop_integral(orientation, expression, skew=Fraction(0), end=Fraction(1)):
    """Simpson between breakpoints, exact for integrands at most quadratic."""
    nu, s, times = signals(orientation, skew)
    times = sorted({t for t in times if t < end} | {end})
    total = Fraction(0)
    for a, b in zip(times, times[1:]):
        middle = (a+b)/2
        rates = (nu[1](middle), s[1](middle))
        values = [expression(nu[0](t), s[0](t), rates[0], rates[1])
                  for t in (a, middle, b)]
        total += (b-a)*(values[0]+4*values[1]+values[2])/6
    return total


def antisymmetric(n, s, n_rate, s_rate):
    return s*n_rate-n*s_rate


def symmetric(n, s, n_rate, s_rate):
    return s*n_rate+n*s_rate


def state_product(n, s, _n_rate, _s_rate):
    return s*n


def proposition_e(orientation):
    """The ordinary store is exact, so only dwell occupancy reaches the impulse."""
    return {"store_loop": loop_integral(orientation, symmetric),
            "occupancy": loop_integral(orientation, state_product)}


@lru_cache(maxsize=2)
def holonomy(orientation):
    """Loop integral of s*dnu/dt - nu*ds/dt, in units where T = 1."""
    return loop_integral(orientation, antisymmetric)


def skew_mean(orientation, skew):
    """Mean of s(t)*nu(t - skew), so the ordinary force is -Fhat times this."""
    return loop_integral(orientation, state_product, skew)


STORE_TAU = Fraction(1, 10)  # tau_s/T for the ledger, a declared test value


def momentum_ledger(orientation, g_units, end=Fraction(1)):
    """Full momentum identity with K = 0 and no actuator, in units of Fhat*T.

    `g_units` is G/(Fhat*T). The assembly and reservoir changes are integrated
    from their force laws. The store and radiation changes come from their own
    states, so the sum is a real check and not a definition.
    """
    nu, s, _ = signals(orientation)

    def assembly_force(n, level, n_rate, s_rate):
        return (-level*n-STORE_TAU*(level*n_rate+n*s_rate)
                + g_units*antisymmetric(n, level, n_rate, s_rate))

    def reservoir_force(n, level, n_rate, s_rate):
        return -g_units*antisymmetric(n, level, n_rate, s_rate)

    assembly = loop_integral(orientation, assembly_force, end=end)
    reservoir = loop_integral(orientation, reservoir_force, end=end)
    radiated = loop_integral(orientation, state_product, end=end)
    store = STORE_TAU*(s[0](end)*nu[0](end)-s[0](Fraction(0))*nu[0](Fraction(0)))
    return {"assembly": assembly, "reservoir": reservoir, "store": store,
            "radiation": radiated, "sum": assembly+reservoir+store+radiated}


def prescribed_work(orientation, g_over_mass, g_units):
    """Work by the added force on a free assembly, with the reservoir held.

    w is constant between breakpoints, because the ramps do not overlap. Returns
    the actuator-supplied work and the kinetic energy it must equal, per unit mass.
    """
    nu, s, times = signals(orientation)
    velocity = work = Fraction(0)
    for a, b in zip(times, times[1:]):
        middle = (a+b)/2
        rates = (nu[1](middle), s[1](middle))
        w_a = antisymmetric(nu[0](a), s[0](a), *rates)
        w_b = antisymmetric(nu[0](b), s[0](b), *rates)
        if w_a != w_b:
            raise OperationalFailure("ramps overlap, so w is not constant")
        next_velocity = velocity+g_over_mass*w_a*(b-a)
        work += g_units*w_a*(velocity+next_velocity)/2*(b-a)
        velocity = next_velocity
    return {"work": work, "kinetic": g_units/g_over_mass*velocity*velocity/2}


def rectangle_integrals():
    """The frozen rectangle in (R, nu), with R in units of the stroke."""
    corners = FREEZE["proposition_M"]["rectangle_R_nu"]
    points = [(Fraction(r), Fraction(n)) for r, n in corners]
    nu_dr = r_dnu = Fraction(0)
    for (r_a, n_a), (r_b, n_b) in zip(points, points[1:]+points[:1]):
        nu_dr += (n_a+n_b)/2*(r_b-r_a)
        r_dnu += (r_a+r_b)/2*(n_b-n_a)
    return {"nu_dR": nu_dr, "R_dnu": r_dnu}


def readout_phase(near, far, phi):
    """Theta of Z = near + exp(i*phi)*far, on the principal branch."""
    return math.atan2(far*math.sin(phi), near+far*math.cos(phi))


def _wrapped(value):
    return math.atan2(math.sin(value), math.cos(value))


def readout_loop(steps=64):
    """Sum the principal increments of Theta round the rectangle, phi through 0."""
    integrals = retained()
    near, far = integrals["I_near"], integrals["I_far"]
    half = math.pi/2
    # Corners in (R index, phi): (0, -pi/2), (1, -pi/2), (1, +pi/2), (0, +pi/2).
    path = [(0, -half), (1, -half)]
    path += [(1, -half+math.pi*i/steps) for i in range(1, steps+1)]
    path.append((0, half))
    path += [(0, half-math.pi*i/steps) for i in range(1, steps+1)]
    total = 0.0
    previous = None
    for index, phi in path:
        value = readout_phase(near[index], far[index], phi)
        if previous is not None:
            total += _wrapped(value-previous)
        previous = value
    return {"sum_radians": total, "phases": [readout_phase(near[i], far[i], p)
                                            for i, p in ((0, -half), (1, -half),
                                                         (1, half), (0, half))]}


def theta_a_rectangle():
    """Root's rectangle: the action's phase alone, which is not the readout."""
    return -retained()["n_hat"]*WAVENUMBER*STROKE*float(rectangle_integrals()["nu_dR"])


def theta_h_rectangle(h):
    integrals = rectangle_integrals()
    return (-h*retained()["n_hat"]*WAVENUMBER*STROKE
            * float(integrals["nu_dR"]+2*integrals["R_dnu"]))


# Conversions and the C2 heuristic.

def natural_units():
    hbar_c = HBAR*C_LIGHT
    return {"metre": ELECTRON/hbar_c,
            "tesla": math.sqrt(hbar_c**3/MU_0)/ELECTRON**2}


def f_est(g_per_gev, channel_watts=None):
    """Heuristic conversion fraction, borrowed from a static-field form. No bound."""
    power = FREEZE["power_map"]["orthogonal_channel_power_watts"]
    channel_watts = power if channel_watts is None else channel_watts
    if not (math.isfinite(g_per_gev) and math.isfinite(channel_watts)):
        raise OperationalFailure("C2 input is not finite")
    units = natural_units()
    waist = float(APERTURE)
    intensity = 2*channel_watts/(math.pi*waist**2)
    field = math.sqrt(2*intensity*MU_0*C_LIGHT)/C_LIGHT
    theta = 2/K_W
    length = K_W*waist/2
    return (g_per_gev*1e-9*theta*field*units["tesla"]*length*units["metre"]/2)**2


def c2_force(g_per_gev, s=1.0):
    """Residual with the dump, assuming all of it reaches x. A lower limit on g."""
    total = FREEZE["power_map"]["orthogonal_channels_P_rad_watts_at_s_1"]*s
    channel = FREEZE["power_map"]["orthogonal_channel_power_watts"]*s
    return f_est(g_per_gev, channel)*total/C_LIGHT


def c2_scope(g_per_gev):
    scope = FREEZE["C2_scope"]
    photon = HBAR*OMEGA/ELECTRON
    return (f_est(g_per_gev) <= scope["maximum_f_est"]
            and abs(g_per_gev)*1e-9*photon <= scope["maximum_g_omega"])


def g_for_force(force):
    unit = f_est(1.0)
    total = FREEZE["power_map"]["orthogonal_channels_P_rad_watts_at_s_1"]
    return math.sqrt(force*C_LIGHT/total/unit)


def c3_scale():
    integrals = retained()
    tau = ELLS[-1]/C_LIGHT
    n0 = integrals["P0"]*tau/(HBAR*OMEGA)
    return {"N0": n0, "Q": integrals["F_hat"]*tau,
            "Q_from_N0": HBAR*n0*WAVENUMBER*integrals["n_hat"]}


def c3_contrast(h, ell):
    """Orientation contrast at the frozen loop, from the exact holonomy."""
    tau = ell/C_LIGHT
    return (h*retained()["F_hat"]*tau*LOOP_FREQUENCY
            * float(holonomy(1)-holonomy(-1)))


def skew_contrast(skew_seconds):
    """Ordinary orientation contrast from a modulator skew, Fhat force units."""
    return -4*retained()["F_hat"]*float(DELTA_S)*LOOP_FREQUENCY*skew_seconds


# Estimator. Observations and widths only.

def width_for(channel, scope):
    """Force channels get benchmark widths. Everything else has no finite map."""
    if scope in HALF_WIDTHS and (channel.startswith("fx_contrast")
                                 or channel.startswith("loop_contrast")):
        return {"kind": "benchmark", "W": 2*HALF_WIDTHS[scope]+MARGIN}
    return {"kind": "unproved", "W": None}


def _finite(value):
    return (isinstance(value, (int, float)) and not isinstance(value, bool)
            and math.isfinite(value))


def _channel_score(a, b, width):
    if width.get("kind") not in WIDTH_KINDS:
        raise OperationalFailure("unknown width status")
    value = width.get("W")
    if (width["kind"] == "unproved" or not _finite(a) or not _finite(b)
            or not _finite(value) or value <= 0):
        return None
    return abs(a-b)/value


def pointwise_sensitivity(candidate, rivals, widths):
    """min over a finite rival grid of max over channels. Unknowns fail closed.

    A channel with no finite score contributes nothing, and it leaves the result
    `unproved` unless a finite channel already separates. A key missing from
    either tuple is unknown, never zero.
    """
    if not rivals:
        raise OperationalFailure("the rival grid is empty")
    worst, kinds, unknown = None, set(), False
    for rival in rivals:
        best = None
        for channel in sorted(set(candidate) | set(rival)):
            width = widths.get(channel, {"kind": "unproved", "W": None})
            score = _channel_score(candidate.get(channel), rival.get(channel), width)
            if score is None:
                unknown = True
                continue
            kinds.add(width["kind"])
            best = score if best is None else max(best, score)
        if best is None:
            return {"score": None, "kinds": sorted(kinds), "unknown_channel": True}
        worst = best if worst is None else min(worst, best)
    return {"score": worst, "kinds": sorted(kinds), "unknown_channel": unknown}


def decide(sensitivity):
    """Benchmark scores are never apparatus qualification, whatever their value."""
    for kind in sensitivity["kinds"]:
        if kind not in WIDTH_KINDS:
            raise OperationalFailure("unknown width status")
    score = sensitivity["score"]
    if score is None or not math.isfinite(score):
        return "unproved"
    if "benchmark" in sensitivity["kinds"]:
        return "benchmark_not_a_bound"
    if score >= 1:
        return "conditional_pipeline_discriminable"
    return "unproved" if sensitivity["unknown_channel"] else "not_separated"


def decision_tuple(candidate, rivals, widths):
    sensitivity = pointwise_sensitivity(candidate, rivals, widths)
    return (sensitivity["score"], tuple(sensitivity["kinds"]),
            sensitivity["unknown_channel"], decide(sensitivity))


# Models. Each returns an observation tuple, and a generator holds these names.

C1_VARIANTS = ("C1-E", "C1-F")
C1_SITUATIONS = ("closed_laboratory", "open_path", "local_absorber", "ray_absorbed_later")


class C1Context:
    """A typed, admissible C1 situation. The declared map turns it into `a`."""

    def __init__(self, variant, situation, a_inf, within_horizon=None):
        if variant not in C1_VARIANTS or situation not in C1_SITUATIONS:
            raise ValueError("unknown C1 variant or situation")
        if not _finite(a_inf) or not 0 <= a_inf <= 1:
            raise ValueError("a_inf is out of domain")
        if variant == "C1-F" and type(within_horizon) is not bool:
            raise ValueError("C1-F needs a declared horizon state")
        if variant == "C1-E" and within_horizon is not None:
            raise ValueError("C1-E has no horizon")
        self.variant = variant
        self.situation = situation
        self.a_inf = a_inf
        self.within_horizon = within_horizon


ROW_C1 = C1Context(**PROTOCOL["c1_context"]["row_context"])


def absorption(context):
    """The assumed, unverified map from a situation to `a`."""
    if context.situation == "open_path":
        return context.a_inf
    if context.variant == "C1-E":
        return 1.0
    return 1.0 if context.within_horizon else context.a_inf


def effective_eta(epsilon, context):
    if not _finite(epsilon) or not -1 <= epsilon <= 1:
        raise ValueError("epsilon is out of domain")
    return epsilon*(1-absorption(context))


def contrast_a_p(eta, f_plus, f_minus):
    plus, minus = 1-eta*f_plus, 1-eta*f_minus
    return (plus-minus)/(plus+minus)


class Context:
    """Declared generator conditions. The estimator never receives one."""

    def __init__(self, c1=ROW_C1, p_theta=False, skew_seconds=0.0, skew_per_tau=0.0,
                 phase_hysteresis=0.0, reflection_amplitude=0.0):
        self.c1 = c1
        self.p_theta = p_theta
        self.skew_seconds = skew_seconds
        self.skew_per_tau = skew_per_tau
        self.phase_hysteresis = phase_hysteresis
        self.reflection_amplitude = reflection_amplitude


def _i2(residual):
    integrals = retained()
    return {"fx_contrast": 0.0, "fy_contrast": integrals["fy_contrast_at_1_W"],
            "residual_no_dump": 0.0, "residual_dump_orthogonal": residual,
            "residual_dump_parallel": 0.0}


def _i3(force_of_s):
    result = {}
    for s in POWER_SCAN:
        force = force_of_s(float(s))
        result[f"residual_{float(s)}"] = force
        result[f"deficit_{float(s)}"] = None if force is None else force*C_LIGHT
    return result


def guarded_force(g, s=1.0):
    """The C2 residual, unknown outside the frozen scope. Dependent rows fail closed."""
    return c2_force(g, s) if c2_scope(g) else None


def observe(model, intervention, coupling, context=None):
    """The noiseless observation tuple for one model, as a dict of channels.

    For C1 the coupling is the fundamental epsilon, and the typed context gives
    `eta`. Rows use the frozen context where the two coincide.
    """
    if model not in MODELS or intervention not in INTERVENTIONS:
        raise ValueError("unknown model or intervention")
    context = Context() if context is None else context
    if not _finite(coupling):
        raise OperationalFailure("coupling is not finite")
    integrals = retained()
    eta = effective_eta(coupling, context.c1) if model == "C1" else 0.0
    g = coupling if model == "C2" else 0.0
    h = coupling if model == "C3" else 0.0
    if intervention == "I1":
        return {"fx_contrast": 2*integrals["F_hat"]*(1-eta)}
    if intervention == "I2":
        return _i2(guarded_force(g))
    if intervention == "I3":
        return _i3(lambda s: guarded_force(g, s))
    if intervention == "I4":
        return {"A_P": contrast_a_p(eta, integrals["f_plus"], integrals["f_minus"])}
    if intervention == "I5":
        # An onset is never asserted apart from a nonzero amplitude.
        step = -eta+context.reflection_amplitude
        if eta != 0.0:
            onset = -1.0
        else:
            onset = 1.0 if context.reflection_amplitude != 0.0 else 0.0
        return {"relative_power_step": step, "event_over_L_c": onset}
    if intervention == "I6":
        result = {}
        for ell in ELLS:
            skew = context.skew_seconds+context.skew_per_tau*ell/C_LIGHT
            result[f"loop_contrast_{ell}"] = c3_contrast(h, ell)+skew_contrast(skew)
        return result
    if h != 0.0 and not context.p_theta:
        return {"loop_phase": None}
    return {"loop_phase": theta_h_rectangle(h)+context.phase_hysteresis}


# Rival generators. Ordinary tuples from their own formulae, with no candidate input.

def leakage_i2(fraction):
    return _i2(fraction*FREEZE["power_map"]["orthogonal_channels_P_rad_watts_at_s_1"]/C_LIGHT)


def leakage_i3(fraction):
    """Ordinary light leaving the box, with loss rising as power, so force as power^2."""
    total = FREEZE["power_map"]["orthogonal_channels_P_rad_watts_at_s_1"]
    return _i3(lambda s: fraction*s*s*total/C_LIGHT)


def matches(a, b, tolerance=ADVERSE["match_relative_tolerance"]):
    """True only when every channel of both tuples is known and agrees."""
    if a.keys() != b.keys():
        return False
    for key in a:
        x, y = a[key], b[key]
        if not _finite(x) or not _finite(y):
            return False
        if abs(x-y) > tolerance*max(abs(x), abs(y)):
            return False
    return True


def same_decision(a, b, rivals, widths):
    """Equal states and scores within the match tolerance, for matched tuples."""
    x, y = pointwise_sensitivity(a, rivals, widths), pointwise_sensitivity(b, rivals, widths)
    if decide(x) != decide(y) or x["kinds"] != y["kinds"]:
        return False
    if x["score"] is None or y["score"] is None:
        return x["score"] is y["score"]
    tolerance = ADVERSE["match_relative_tolerance"]
    return abs(x["score"]-y["score"]) <= tolerance*max(abs(x["score"]), abs(y["score"]))


def _case(name, observation, outcome, cause, **extra):
    result = {"case": name, "observation": observation, "outcome": outcome, "cause": cause}
    result.update(extra)
    return result


def _c1_cases(intervention):
    probes = ADVERSE["probes"]
    epsilon, a_inf = probes["epsilon"], probes["a_inf"]
    reference = observe("B0", intervention, 0.0)
    contexts = (
        ("C1-E_ray_absorbed_later", C1Context("C1-E", "ray_absorbed_later", a_inf)),
        ("C1-E_closed_laboratory", C1Context("C1-E", "closed_laboratory", a_inf)),
        ("C1-E_opaque_future_a_inf_1", C1Context("C1-E", "open_path", 1.0)),
        ("C1-E_open_path_at_probe", C1Context("C1-E", "open_path", a_inf)),
        ("C1-F_later_absorber_within_horizon",
         C1Context("C1-F", "ray_absorbed_later", a_inf, True)),
        ("C1-F_later_absorber_beyond_horizon",
         C1Context("C1-F", "ray_absorbed_later", a_inf, False)))
    cases = []
    for name, c1 in contexts:
        eta = effective_eta(epsilon, c1)
        observation = observe("C1", intervention, epsilon, Context(c1=c1))
        same = distinct(observation, reference) is False
        if eta == 0.0 and not same:
            raise OperationalFailure("a declared null differs from B0")
        cases.append(_case(
            name, observation,
            "exact_null_by_hypothesis_map" if eta == 0.0 else "unconstrained_open",
            "a_equals_1_so_eta_is_0" if eta == 0.0 else "eta_nonzero_a_inf_assumed",
            epsilon=epsilon, a=absorption(c1), eta=eta))
    transferred = probes["transferred_abs_eta_illustrative"]
    cases.append(_case(
        "secondary_illustrative_constraint", observe("C1", intervention, transferred),
        "secondary_illustrative_constraint_no_credit",
        "second_hand_3_cm_value_primary_unread_critiques_unresolved", eta=transferred))
    if intervention == "I5":
        reflection = observe("B0", "I5", 0.0, Context(
            reflection_amplitude=probes["reflection_amplitude"]))
        cases.append(_case("back_reflection", reflection, "unproved",
                           "synthetic_amplitude_no_finite_timing_map"))
    return cases


def c2_scope_limit():
    """Twice the coupling at the conversion bound, so plainly outside the scope."""
    return 2*math.sqrt(FREEZE["C2_scope"]["maximum_f_est"]/f_est(1.0))


def _c2_cases(intervention):
    g = ADVERSE["probes"]["g_per_GeV"]
    candidate = observe("C2", intervention, g)
    rivals = [observe("B0", intervention, 0.0)]
    widths = {key: width_for(key, None) for key in candidate}
    fraction = f_est(g)
    leaked = leakage_i2(fraction) if intervention == "I2" else leakage_i3(fraction)
    matched = matches(candidate, leaked)
    gated = leakage_i2(0.0) if intervention == "I2" else leakage_i3(0.0)
    outside = observe("C2", intervention, c2_scope_limit())
    return [
        _case("leakage_matched", leaked,
              "finite_rival_unresolved" if matched else "unproved",
              "ordinary_leak_gives_the_same_tuple_with_no_joint_map",
              matched=matched, same_decision=same_decision(candidate, leaked, rivals, widths)),
        _case("gated_absorption_inside_box", gated, "unproved",
              "heat_stays_in_the_box_only_a_finite_heat_and_force_map_could_separate",
              matched=matches(candidate, gated)),
        _case("outside_scope_fails_closed", outside, "unproved", "outside_C2_scope",
              g_per_GeV=c2_scope_limit(), known=all(_finite(v) for v in outside.values()))]


def _c3_i6_cases(scope):
    h = ADVERSE["probes"]["h"]
    candidate = observe("C3", "I6", h)
    rivals = [observe("B0", "I6", 0.0)]
    widths = {key: width_for(key, scope) for key in candidate}
    following = observe("B0", "I6", 0.0, Context(skew_per_tau=2*h))
    tau = ELLS[-1]/C_LIGHT
    invariant = observe("B0", "I6", 0.0, Context(skew_seconds=2*h*tau))
    agreeing = [key for key in sorted(candidate)
                if matches({key: candidate[key]}, {key: invariant[key]})]
    matched = matches(candidate, following)
    return [
        _case("ell_following_skew_matched", following,
              "finite_rival_unresolved" if matched else "unproved",
              "skew_following_ell_is_an_exact_degeneracy", matched=matched,
              same_decision=same_decision(candidate, following, rivals, widths)),
        _case("ell_invariant_skew", invariant, "unproved",
              "ell_scan_separates_only_a_declared_invariant_skew",
              matched=False, agreeing_channels=agreeing)]


def _c3_i7_cases():
    h = ADVERSE["probes"]["h"]
    ideal = observe("C3", "I7", h, Context(p_theta=True))
    hysteresis = observe("B0", "I7", 0.0, Context(phase_hysteresis=theta_h_rectangle(h)))
    rivals = [observe("B0", "I7", 0.0)]
    widths = {"loop_phase": width_for("loop_phase", None)}
    matched = matches(ideal, hysteresis)
    return [
        _case("phase_hysteresis_matched", hysteresis,
              "finite_rival_unresolved" if matched else "unproved",
              "ordinary_hysteresis_gives_the_same_loop_phase", matched=matched,
              same_decision=same_decision(ideal, hysteresis, rivals, widths)),
        _case("ideal_branch_under_P_theta", ideal, "conditional_on_premise",
              "P_theta_is_unproved_this_branch_earns_no_apparatus_score")]


def adverse_cases(model, intervention, scope):
    """Declared cases at frozen probes. They add no row and no configuration."""
    if model == "C1" and intervention in DISCRIMINATORS["C1"]:
        return _c1_cases(intervention)
    if model == "C2" and intervention in DISCRIMINATORS["C2"]:
        return _c2_cases(intervention)
    if model == "C3" and intervention == "I6":
        return _c3_i6_cases(scope)
    if model == "C3" and intervention == "I7":
        return _c3_i7_cases()
    return []


def declared_adverse(model, intervention):
    if model == "C1" and intervention in DISCRIMINATORS["C1"]:
        names = list(ADVERSE["C1"])
        return names+list(ADVERSE["C1_I5_extra"]) if intervention == "I5" else names
    if model == "C2" and intervention in DISCRIMINATORS["C2"]:
        return list(ADVERSE["C2"])
    if model == "C3" and intervention in DISCRIMINATORS["C3"]:
        return list(ADVERSE["C3_"+intervention])
    return []


# Hypotheses.

def distinct(a, b):
    """True if a known channel differs, False if all agree, None if unknown.

    An unknown channel never supports distinctness. A channel missing from one
    tuple is unknown, and None against None is unknown too.
    """
    unknown = False
    for key in sorted(set(a) | set(b)):
        x, y = a.get(key), b.get(key)
        if not _finite(x) or not _finite(y):
            unknown = True
        elif x != y:
            return True
    return None if unknown else False


def _status(failures, unknown=()):
    if failures:
        status = "refuted"
    elif unknown:
        status = "unproved"
    else:
        status = "supported"
    return {"status": status, "causes": list(failures)+list(unknown)}


def grid(model):
    name = {"C1": "eta", "C2": "g_per_GeV", "C3": "h"}[model]
    return tuple(PROTOCOL["coupling_grids"][name])


def h1_recovery():
    failures = []
    for model in ("C1", "C2", "C3"):
        for intervention in INTERVENTIONS:
            if distinct(observe(model, intervention, 0.0),
                        observe("B0", intervention, 0.0)) is not False:
                failures.append(f"{model}_{intervention}")
    return _status(failures)


def h2_distinct(observer=None):
    """Effective coupling only. I7 sits in a separate ideal branch under P-theta."""
    observer = observe if observer is None else observer
    failures, unknown, conditional = [], [], []
    ideal = Context(p_theta=True)
    for model in ("C1", "C2", "C3"):
        for value in grid(model):
            if value == 0.0:
                continue
            for intervention in DISCRIMINATORS[model]:
                result = distinct(observer(model, intervention, value),
                                  observer("B0", intervention, 0.0))
                if result is None and model == "C3" and intervention == "I7":
                    branch = distinct(observer(model, intervention, value, ideal),
                                      observer("B0", intervention, 0.0, ideal))
                    if branch is True:
                        conditional.append(value)
                        continue
                    result = branch
                if result is None:
                    unknown.append(f"{model}_{intervention}_{value}")
                elif result is False:
                    failures.append(f"{model}_{intervention}_{value}")
    for a, b in (("C1", "C2"), ("C1", "C3"), ("C2", "C3")):
        for x in grid(a):
            for y in grid(b):
                if x == 0.0 or y == 0.0:
                    continue
                results = [distinct(observer(a, i, x), observer(b, i, y)) for i in INTERVENTIONS]
                if True not in results:
                    (unknown if None in results else failures).append(f"{a}_{x}_{b}_{y}")
    result = _status(failures, unknown)
    result["I7_conditional_on_P_theta"] = len(conditional)
    return result


def h3_force_gap():
    """On the frozen finite grids only. Nothing is stated above the g grid."""
    reached, unknown = {}, []
    for scope, half in HALF_WIDTHS.items():
        gap = 2*half+MARGIN
        for model in ("C1", "C2", "C3"):
            for value in grid(model):
                if model == "C1":
                    change = abs(2*retained()["F_hat"]*effective_eta(value, ROW_C1))
                elif model == "C2":
                    change = guarded_force(value)
                else:
                    change = abs(c3_contrast(value, ELLS[-1]))
                if change is None:
                    unknown.append(f"{model}_{scope}_{value}")
                elif change >= gap:
                    reached.setdefault(f"{model}_{scope}", []).append(value)
    failures = [key for key in reached if key.endswith("S05") or key == "C3_S01"]
    result = _status(failures, unknown)
    result["reached"] = reached
    return result


def h4_ratios():
    force = c2_force(0.66e-10)
    required = g_for_force(1e-12)
    limits = (0.66e-10, 5.45e-7)
    result = _status([] if all(required > limit for limit in limits)
                     else ["required_g_below_a_limit_read"])
    result.update(coupling_decades=math.log10(required/0.66e-10),
                  force_decades=math.log10(1e-12/force), required_g=required,
                  credit="none_heuristic")
    return result


def h5_c1_maps():
    integrals = retained()
    tolerance = QUADRATURE["oracle_float_relative_tolerance"]
    failures = []
    expected = {"C1-E_ray_absorbed_later": True, "C1-E_closed_laboratory": True,
                "C1-E_opaque_future_a_inf_1": True, "C1-E_open_path_at_probe": False,
                "C1-F_later_absorber_within_horizon": True,
                "C1-F_later_absorber_beyond_horizon": False}
    for intervention in DISCRIMINATORS["C1"]:
        for case in adverse_cases("C1", intervention, None):
            if case["case"] in expected:
                null = case["outcome"] == "exact_null_by_hypothesis_map"
                if null != expected[case["case"]]:
                    failures.append(f"{intervention}_{case['case']}")
    for eta in grid("C1"):
        value = contrast_a_p(eta, integrals["f_plus"], integrals["f_minus"])
        closed = -integrals["D_f"]*eta/(2-eta)
        if abs(value-closed) > tolerance*max(abs(closed), 1e-12):
            failures.append(f"A_P_{eta}")
    return _status(failures)


def h6_identities():
    failures = []
    for orientation in ORIENTATIONS:
        if proposition_e(orientation)["store_loop"] != 0:
            failures.append(f"store_{orientation}")
        ledger = momentum_ledger(orientation, Fraction(3, 10))
        if ledger["sum"] != 0:
            failures.append(f"momentum_{orientation}")
        partial = momentum_ledger(orientation, Fraction(3, 10), Fraction(5, 16))
        if partial["sum"] != 0:
            failures.append(f"momentum_partial_{orientation}")
        energy = prescribed_work(orientation, Fraction(1, 7), Fraction(3, 10))
        if energy["work"] != energy["kinetic"]:
            failures.append(f"work_{orientation}")
    if proposition_e(1)["occupancy"] != proposition_e(-1)["occupancy"]:
        failures.append("occupancy_order_dependent")
    result = _status(failures)
    result["autonomous_case"] = "unproved"
    return result


def h7_skew():
    failures = []
    # x = h*tau_s*f on a rational ell scan, so C3's mean is x*holonomy in Fhat units.
    scan = (Fraction(1, 800), Fraction(1, 400), Fraction(1, 200))
    c3_means = [holonomy(1)*x for x in scan]
    following = [-skew_mean(1, 2*x) for x in scan]
    if following != c3_means:
        failures.append("following_skew_is_not_degenerate")
    # A declared invariant skew matches one ell, and then differs from the others.
    invariant = [-skew_mean(1, 2*scan[-1]) for _ in scan]
    if sum(a != b for a, b in zip(invariant, c3_means)) != len(scan)-1:
        failures.append("invariant_skew_is_not_separated")
    result = _status(failures)
    result["ell_invariant_skew"] = "separated_by_the_ell_scan_as_declared"
    result["ell_following_skew"] = "exact_degeneracy_force_alone_cannot_separate"
    return result


def h8_pairing(scope="S01"):
    """Identical tuples decide identically, and so do generated matched rivals."""
    failures = []
    for intervention in INTERVENTIONS:
        truth = observe("C3", intervention, 0.1, Context(p_theta=True))
        widths = {key: width_for(key, scope) for key in truth}
        rivals = [observe("B0", intervention, 0.0)]
        if decision_tuple(truth, rivals, widths) != decision_tuple(dict(truth), rivals, widths):
            failures.append(intervention)
    for model, intervention in (("C2", "I2"), ("C2", "I3"), ("C3", "I6"), ("C3", "I7")):
        for case in adverse_cases(model, intervention, scope):
            if case.get("matched") and not case.get("same_decision"):
                failures.append(f"{model}_{intervention}_{case['case']}")
    return _status(failures)


def h9_readout():
    enclosure = winding_enclosure()
    loop = readout_loop()
    tolerance = QUADRATURE["oracle_float_relative_tolerance"]
    if not enclosure["proved"]:
        return {"status": "unproved", "winding": "unproved", "causes": [enclosure["cause"]],
                "enclosure": enclosure}
    failures = [] if abs(loop["sum_radians"]) <= tolerance else ["readout_did_not_close"]
    result = _status(failures)
    result.update(winding=0, enclosure=enclosure, readout_loop_radians=loop["sum_radians"],
                  theta_A_radians=theta_a_rectangle(), state="derived_in_declared_model")
    return result


HYPOTHESES = {"H1": h1_recovery, "H2": h2_distinct, "H3": h3_force_gap, "H4": h4_ratios,
              "H5": h5_c1_maps, "H6": h6_identities, "H7": h7_skew, "H8": h8_pairing,
              "H9": h9_readout}


# Rows and records.

def row_outcome(model, intervention, value, state, score):
    """A gap met on a benchmark stays `unproved`. It qualifies no apparatus."""
    if model == "C2" and intervention in DISCRIMINATORS["C2"] and value != 0.0:
        return "heuristically_far_below_target_conditional"
    if model == "C3" and intervention == "I7" and value != 0.0:
        return "conditional_on_premise"
    if state == "benchmark_not_a_bound" and score < 1:
        return "benchmark_force_gap_not_met"
    return "unproved"


def evaluate_row(model, intervention, scope):
    """Every value on the row's frozen grid, plus its declared adverse cases."""
    values = (0.0,) if model == "B0" else grid(model)
    reference = [observe("B0", intervention, 0.0)]
    entries = []
    for value in values:
        observation = observe(model, intervention, value)
        widths = {key: width_for(key, scope) for key in observation}
        sensitivity = pointwise_sensitivity(observation, reference, widths)
        state = decide(sensitivity)
        entry = {"coupling": value, "observation": observation,
                 "score_against_B0": sensitivity["score"], "state": state,
                 "unknown_channel": sensitivity["unknown_channel"],
                 "outcome": row_outcome(model, intervention, value, state,
                                        sensitivity["score"])}
        if model == "C3" and intervention == "I7":
            entry["loop_phase_under_P_theta"] = theta_h_rectangle(value)
        entries.append(entry)
    return {"model": model, "intervention": intervention, "scope": scope, "entries": entries,
            "coupling_kind": {"C1": "effective_eta_at_the_row_context"}.get(model, "declared"),
            "label": "pointwise_conditional_sensitivity",
            "adverse": adverse_cases(model, intervention, scope)}


def canonical(record):
    return json.dumps(record, sort_keys=True, separators=(",", ":"),
                      allow_nan=False).encode("utf-8")


def enforce_record_budget(record):
    data = canonical(record)
    limits = PROTOCOL["limits"]
    if len(data) > limits["maximum_retained_bytes"]:
        raise OperationalFailure("record exceeds its byte limit")
    parsed = json.loads(data.decode("utf-8"))
    nodes = sum(1 for _ in rules.walk(parsed))
    if nodes > limits["maximum_parser_nodes"]:
        raise OperationalFailure("record exceeds its node limit")
    bound = PROTOCOL["lean_record"]["maximum_bytes_per_configuration"]
    for row in record["rows"]:
        if len(canonical(row)) > bound:
            raise OperationalFailure("row exceeds its byte limit")
    return len(data)


KIND = {"fixture": PRIMARY["fixture_kind"], PRIMARY["source_mode"]: PRIMARY["kind"]}
STATUS = {"fixture": "virtual_lab_fixture_not_a_primary_not_physical_evidence",
          PRIMARY["source_mode"]: "virtual_lab_deterministic_primary_not_physical_evidence"}


def expected_rows(mode):
    return tuple(rows()) if mode == PRIMARY["source_mode"] else FIXTURE_ROWS


def check_record(record, mode):
    """Kind, mode, rows, hypotheses and adverse cases are checked together.

    A fixture cannot pass as a primary, or a primary as a fixture.
    """
    if mode not in KIND:
        raise OperationalFailure("unknown record mode")
    if (record.get("kind") != KIND[mode] or record.get("status") != STATUS[mode]
            or record.get("source", {}).get("mode") != mode
            or record.get("environment") != ENVIRONMENT):
        raise OperationalFailure("record identity does not match its mode")
    keys = [(row["model"], row["intervention"], row["scope"]) for row in record["rows"]]
    wanted = expected_rows(mode)
    if len(keys) != len(wanted) or len(set(keys)) != len(keys) or set(keys) != set(wanted):
        raise OperationalFailure("record rows do not match its mode")
    for row in record["rows"]:
        names = [case["case"] for case in row["adverse"]]
        if names != declared_adverse(row["model"], row["intervention"]):
            raise OperationalFailure("row lacks its declared adverse cases")
    if mode == PRIMARY["source_mode"]:
        if sorted(record.get("hypotheses", {})) != PRIMARY["required_hypotheses"]:
            raise OperationalFailure("primary lacks a hypothesis")
    elif "hypotheses" in record:
        raise OperationalFailure("a fixture holds no hypotheses")


def mode_authorised(mode):
    """The deterministic primary stays refused. A fixture is never a primary."""
    if mode == "fixture":
        return True
    return mode == PRIMARY["source_mode"] and rules.primary_authorised(PROTOCOL)


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


def runtime_statement(launch):
    """Hashes only. No record holds a path, and the wrapper's vector comes as a hash."""
    vector = list(getattr(sys, "orig_argv", [sys.executable, *sys.argv]))
    with open(os.path.realpath(sys.executable), "rb") as source:
        executable = source.read(MAX_EXECUTABLE_BYTES+1)
    if len(executable) > MAX_EXECUTABLE_BYTES:
        raise OperationalFailure("runtime executable exceeds its read limit")
    return {"python": platform.python_version(),
            "implementation": platform.python_implementation(),
            "machine": platform.machine(), "system": platform.system(),
            "version_sha256": _digest(sys.version.encode("utf-8")),
            "executable_sha256": _digest(executable),
            "study_argv_sha256": _digest(json.dumps(vector, separators=(",", ":")).encode("utf-8")),
            "wrapper_argv_sha256": launch}


def _base(mode, commit, opened, launch):
    return {"study": PROTOCOL["study"], "protocol_revision": PROTOCOL["protocol_revision"],
            "environment": ENVIRONMENT, "kind": KIND[mode], "status": STATUS[mode],
            "source": {"commit": commit, "mode": mode},
            "runtime": runtime_statement(launch), "implementation": opened}


def fixture_record(commit, opened, launch, *, evaluate=None):
    """The declared subset, with a measured estimate for the record budget."""
    evaluate = evaluate_row if evaluate is None else evaluate
    record = _base("fixture", commit, opened, launch)
    record["rows"] = [evaluate(*row) for row in FIXTURE_ROWS]
    record["winding_enclosure"] = winding_enclosure()
    used = enforce_record_budget(record)
    largest = max(len(canonical(row)) for row in record["rows"])
    record["budget"] = {"fixture_bytes_before_this_field": used, "largest_row_bytes": largest,
                        "projected_36_row_bytes": used+largest*(len(rows())-len(record["rows"])),
                        "limit_bytes": PROTOCOL["limits"]["maximum_retained_bytes"]}
    return record


def primary_record(commit, opened, launch, *, evaluate=None, hypotheses=None):
    """All 36 rows and H1 to H9. Tests reach it on stubs only."""
    evaluate = evaluate_row if evaluate is None else evaluate
    hypotheses = HYPOTHESES if hypotheses is None else hypotheses
    record = _base(PRIMARY["source_mode"], commit, opened, launch)
    record["rows"] = [evaluate(*row) for row in rows()]
    record["hypotheses"] = {name: function() for name, function in hypotheses.items()}
    record["winding_enclosure"] = winding_enclosure()
    record["c1_grid_meaning"] = PROTOCOL["c1_context"]["grid_meaning"]
    return record


BUILDERS = {"fixture": fixture_record, PRIMARY["source_mode"]: primary_record}


def run_mode(mode, commit, launch, *, root=ROOT.parent.parent, builders=None):
    """Refuses unless authorised, then builds and checks under the boundary."""
    if not mode_authorised(mode):
        raise OperationalFailure("execution is not authorised by the protocol")
    if not (isinstance(commit, str) and len(commit) == 40
            and all(ch in "0123456789abcdef" for ch in commit)):
        raise ValueError("a full source commit is required")
    if not (isinstance(launch, str) and len(launch) == 64
            and all(ch in "0123456789abcdef" for ch in launch)):
        raise ValueError("a launch hash is required")
    builder = (BUILDERS if builders is None else builders)[mode]

    def build(opened):
        record = builder(commit, opened, launch)
        check_record(record, mode)
        enforce_record_budget(record)
        return record
    return inputs.bound_run(root, ROOT, commit, build)


def main(arguments=None):
    arguments = sys.argv[1:] if arguments is None else arguments
    if not arguments or arguments[0] not in MODES or not mode_authorised(arguments[0]):
        print("execution is not authorised by the protocol", file=sys.stderr)
        return 3
    if (len(arguments) != 7 or arguments[1] != "--commit" or arguments[3] != "--launch"
            or arguments[5] != "--result-fd"):
        print("usage: MODE --commit COMMIT --launch SHA256 --result-fd FD", file=sys.stderr)
        return 2
    record = run_mode(arguments[0], arguments[2], arguments[4])
    with open(int(arguments[6]), "wb") as sink:
        sink.write(canonical(record))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
