"""PF-002 mechanistic robustness study, version 1.

Virtual lab only. Exact worst-case channel envelopes over a declared box,
adversarial witnesses through the committed channel code, and fresh-seed
cohorts. Parameters come from the frozen protocol JSON. No physical
calibration, hardware capability or propulsion result is claimed.
"""

from dataclasses import replace
import hashlib
from itertools import product
import json
import math
from pathlib import Path
import random
import sys

from coupled_differential_optical_v2 import (
    DETECTOR, PRIMARY, REFERENCE, SOURCE, map_interval)
from differential_instrument import acquire as acquire_channels, tail_mean
from optical_driver import predict
from trial_detector import acquire_trial, analyse_trial
from virtual_acquisition import acquire as acquire_optical
from virtual_instruments import Balance

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-mechanistic-robustness-v1-protocol.json"
PROTOCOL = json.loads((ROOT/PROTOCOL_FILE).read_text(encoding="utf-8"))
ACQ = PROTOCOL["acquisition"]
BASE = PROTOCOL["baseline"]
FACTORS = PROTOCOL["factors"]
TRIALS = ACQ["trials"]
SAMPLES = ACQ["samples_per_trial"]
STEP = ACQ["step_seconds"]
TAIL = ACQ["tail_samples"]
COMMON = ACQ["common_force_newtons"]
WEIGHT = ACQ["weight"]
REQUIRED = PROTOCOL["required_margin_newtons"]
STRUCTURAL = PROTOCOL["structural_allowance_per_phase_newtons"]
FLIP = PROTOCOL["orientation_flip_gain_bound"]
GUARD = PROTOCOL["numerical_allowance_newtons"]
BAND = PROTOCOL["vibration_band_hertz"]
OUT_OF_WINDOW = PROTOCOL["out_of_window_impostor_force_newtons"]
WORST_AGE = PROTOCOL["optical_envelope"]["worst_age_seconds"]
PHASE_POINTS = PROTOCOL["optical_envelope"]["phase_lattice_points"]
FEED_POINTS = PROTOCOL["optical_envelope"]["feed_lattice_points"]
QUARTER = math.pi/2
IMPLEMENTATION = (
    "pf002_mechanistic_robustness_v1.py", "pf002_robustness_oracle_v1.py",
    "PF002_MECHANISTIC_ROBUSTNESS_V1.md", PROTOCOL_FILE,
    "coupled_differential_optical_v2.py", "differential_instrument.py",
    "virtual_acquisition.py", "trial_detector.py",
    "detector_qualification.py", "detector_stability.py",
    "virtual_instruments.py", "recoil_budget.py",
    "optical_driver.py", "optical_reference.py",
)
CONTROLS = ("opposite-phase", "phase-null", "force-decoupled",
            "impostor-lab-fixed-in-window",
            "impostor-source-fixed-in-window")
ORDERS = tuple(tuple(s for pair in pattern for s in pair)
               for pattern in product(((1, -1), (-1, 1)), repeat=4))


def _digest(name):
    path = ROOT/name
    if path.stat().st_size > 1048576:
        raise ValueError("study input exceeds 1 MiB")
    return "sha256:"+hashlib.sha256(path.read_bytes()).hexdigest()


def configuration(factors=(), **overrides):
    config = dict(BASE)
    for name in factors:
        config.update(FACTORS[name])
    unknown = set(overrides)-set(config)-{"read_noise_scale",
                                          "structural_allowance_scale"}
    if unknown:
        raise ValueError(f"unsupported configuration keys: {sorted(unknown)}")
    config["read_noise_scale"] = 1.0
    config["structural_allowance_scale"] = 1.0
    config.update(overrides)
    return config


def named_configurations():
    names = tuple(FACTORS)
    rows = [("baseline", ())]
    rows += [(f"only-{name}", (name,)) for name in names]
    rows += [("all", names)]
    rows += [(f"drop-{name}", tuple(n for n in names if n != name))
             for name in names]
    return rows


def channels(config):
    scale = config["read_noise_scale"]
    primary = replace(PRIMARY,
                      noise_bound_newtons=config["primary_noise_newtons"]*scale)
    reference = replace(
        REFERENCE,
        response_seconds=config["reference_response_seconds"],
        thermal_seconds=config["reference_thermal_seconds"],
        thermal_newtons_per_watt=config["reference_thermal_newtons_per_watt"],
        noise_bound_newtons=config["reference_noise_newtons"]*scale)
    return primary, reference


def stationarity(config):
    """A wander cannot exceed a bound claimed to hold at all times."""
    return (min(config["gain_stationarity"], config["calibration_knowledge"]),
            min(config["weight_stationarity"], config["weight_knowledge"]))


def transfer_box(config):
    """Corner envelope of the steady transfer; leakage cannot be negative."""
    dg = config["calibration_knowledge"]
    dw = config["weight_knowledge"]
    dl = config["leakage_knowledge"]
    leak = config["leakage"]
    values = [(1+gp)-w*l*(1+gr) for gp, gr, w, l in product(
        (PRIMARY.calibration_fraction-dg, PRIMARY.calibration_fraction+dg),
        (REFERENCE.calibration_fraction-dg, REFERENCE.calibration_fraction+dg),
        (WEIGHT-dw, WEIGHT+dw),
        (max(0.0, leak-dl), leak+dl))]
    return [min(values), max(values)]


def tail_coefficients(balance):
    """Tail-mean response to unit trial inputs by stepping the channel update.

    Matrix entry [i][j] is the mean mechanical state over the tail of trial i
    for a unit input held during trial j only, from a cold start.
    """
    a = -math.expm1(-STEP/balance.thermal_seconds)
    b = -math.expm1(-STEP/balance.response_seconds)
    kappa = balance.thermal_newtons_per_watt
    matrices = ([[0.0]*TRIALS for _ in range(TRIALS)],
                [[0.0]*TRIALS for _ in range(TRIALS)])
    for matrix, (unit_force, unit_heat) in zip(matrices, ((1.0, 0.0),
                                                          (0.0, 1.0))):
        for j in range(TRIALS):
            thermal = mechanical = 0.0
            for i in range(j, TRIALS):
                force, heat = (unit_force, unit_heat) if i == j else (0.0, 0.0)
                tail = 0.0
                for sample in range(1, SAMPLES+1):
                    thermal += a*(heat*kappa-thermal)
                    mechanical += b*(force+thermal-mechanical)
                    if sample > SAMPLES-TAIL:
                        tail += mechanical
                matrix[i][j] = tail/TAIL
    return matrices


_coefficient_cache = {}


def _coefficients(balance):
    key = (balance.response_seconds, balance.thermal_seconds,
           balance.thermal_newtons_per_watt)
    if key not in _coefficient_cache:
        _coefficient_cache[key] = tail_coefficients(balance)
    return _coefficient_cache[key]


def _tail_time(i):
    """Mean sample time over the tail of zero-based trial i."""
    return i*SAMPLES*STEP+(2*SAMPLES-TAIL+1)*STEP/2


_unit_cache = {}


def _unit(phase):
    """Source fraction and recoil at unit feed; both scale with feed exactly."""
    if phase not in _unit_cache:
        source = predict(SOURCE["wavelength_m"], SOURCE["aperture_radius_m"],
                         SOURCE["separation_m"], phase, 1.0,
                         SOURCE["laser_conversion_efficiency"],
                         SOURCE["control_power_watts"])
        _unit_cache[phase] = (
            source["radiated_fraction_of_optical_feed"],
            source["outgoing_radiation_recoil_component_newtons_xyz"][0])
    return _unit_cache[phase]


def recoil(phase, feed):
    return feed*SOURCE["optical_feed_watts"]*_unit(phase)[1]


def heat(phase, feed):
    power = feed*SOURCE["optical_feed_watts"]
    return (power/SOURCE["laser_conversion_efficiency"]
            - power*_unit(phase)[0]+SOURCE["control_power_watts"])


_detector_cache = {}


def detector_interval(phase, power, end):
    key = (phase, power, end)
    if key not in _detector_cache:
        public, _ = acquire_trial(
            phase_radians=phase, escaping_power_watts=power, end_seconds=end,
            grid=DETECTOR["grid"], cone_degrees=DETECTOR["cone_degrees"],
            pointing_bound_degrees=DETECTOR["pointing_bound_degrees"],
            gain_bound=DETECTOR["gain_bound"],
            total_power_bound_watts=DETECTOR["total_power_bound_watts"],
            additive_error_watts=1e-5, gain_drift_per_second=1e-6,
            power_drift_watts_per_second=1e-6,
            wavelength_m=SOURCE["wavelength_m"],
            aperture_radius_m=SOURCE["aperture_radius_m"],
            separation_m=SOURCE["separation_m"])
        _detector_cache[key] = analyse_trial(public)
    return _detector_cache[key]


def _lattice(centre, half, points):
    if half == 0:
        return [centre]
    return [centre+half*(2*k/(points-1)-1) for k in range(points)]


_window_cache = {}


def optical_window(phase_jitter, feed_variation):
    """Numerical optical envelope; the detector analysis is piecewise.

    This is a lattice envelope with an adjacent-change remainder, not a proof.
    Returns source-frame positive contrasts for the recoil-positive mapping.
    """
    key = (phase_jitter, feed_variation)
    if key in _window_cache:
        return _window_cache[key]
    positive = QUARTER if recoil(QUARTER, 1) > 0 else -QUARTER
    feeds = _lattice(1.0, feed_variation, FEED_POINTS)
    walk_phase = (-phase_jitter, 0.0, phase_jitter) if phase_jitter else (0.0,)
    walk_feed = (-feed_variation, 0.0, feed_variation) if feed_variation else (0.0,)

    def side(base):
        lows, highs = [], []
        for feed in feeds:
            low_row, high_row = [], []
            for phase in _lattice(base, phase_jitter, PHASE_POINTS):
                power = feed*SOURCE["optical_feed_watts"]*_unit(phase)[0]
                low, high = detector_interval(phase, power, WORST_AGE)
                low_row.append(low)
                high_row.append(high)
            lows.append(low_row)
            highs.append(high_row)
        change = 0.0
        for table in (lows, highs):
            for row in table:
                change = max(change, *[abs(x-y) for x, y in zip(row, row[1:])],
                             0.0)
            for upper, lower in zip(table, table[1:]):
                change = max(change, *[abs(x-y) for x, y in zip(upper, lower)])
        return (min(map(min, lows)), max(map(max, highs)), change)

    p_low, p_high, p_change = side(positive)
    n_low, n_high, n_change = side(-positive)
    remainder = p_change+n_change
    walk, strength_min, strength_max, heat_min, heat_max = 0.0, {}, {}, [], []
    for base in (positive, -positive):
        values = []
        for phase, feed, psi, xi in product(
                _lattice(base, phase_jitter, PHASE_POINTS), feeds,
                walk_phase, walk_feed):
            actual = recoil(phase+psi, feed*(1+xi))
            walk = max(walk, abs(actual-recoil(phase, feed)))
            values.append(actual)
            power = heat(phase+psi, feed*(1+xi))
            heat_min.append(power)
            heat_max.append(power)
        strength_min[base], strength_max[base] = min(values), max(values)
    result = {
        "optical_minimum_newtons": p_low-n_high-remainder,
        "optical_maximum_newtons": p_high-n_low+remainder,
        "lattice_remainder_newtons": remainder,
        "walk_newtons": 2*walk,
        "signal_minimum_newtons":
            strength_min[positive]-strength_max[-positive],
        "signal_maximum_newtons":
            strength_max[positive]-strength_min[-positive],
        "heat_minimum_watts": min(heat_min),
        "heat_maximum_watts": max(heat_max),
    }
    _window_cache[key] = result
    return result


def nominal_contrast():
    """Nominal recoil contrast from the committed optical model at unit feed."""
    return 2*abs(recoil(QUARTER, 1))


def _weights(config):
    """Largest admissible weight magnitude, amendment 1."""
    return abs(WEIGHT)+config["weight_knowledge"]


def noise_term(config):
    primary, reference = channels(config)
    _, s_w = stationarity(config)
    return 2*(primary.noise_bound_newtons
              + (_weights(config)+s_w)*reference.noise_bound_newtons)


def gain_term(config, primary_level, reference_level):
    s_g, s_w = stationarity(config)
    return 2*(s_g*primary_level
              + (_weights(config)+s_w)*s_g*reference_level
              + s_w*reference_level)


def vibration_term(config):
    _, s_w = stationarity(config)
    kernel = 1/(TAIL*math.sin(math.pi*BAND[0]*STEP))
    return (2*(PRIMARY.vibration_newtons
               + (_weights(config)+s_w)*REFERENCE.vibration_newtons)*kernel)


def _corners(config):
    dg, dw = config["calibration_knowledge"], config["weight_knowledge"]
    return tuple(product(
        (PRIMARY.calibration_fraction-dg, PRIMARY.calibration_fraction+dg),
        (REFERENCE.calibration_fraction-dg, REFERENCE.calibration_fraction+dg),
        (WEIGHT-dw, WEIGHT+dw)))


def _levels(config, primary, reference, gp, gr, force, ref_force, heat_level):
    gm, hm = _coefficients(primary)
    gr_m, hr_m = _coefficients(reference)
    coupling = config["reference_common_coupling"]
    heat_coupling = config["reference_heat_coupling"]
    p_level, r_level = 0.0, 0.0
    for i in range(TRIALS):
        p = (1+gp)*(sum(gm[i][j]*force for j in range(TRIALS))
                    + sum(hm[i][j]*heat_level for j in range(TRIALS)))
        r = (1+gr)*(sum(gr_m[i][j]*(coupling*COMMON+ref_force)
                        for j in range(TRIALS))
                    + sum(hr_m[i][j]*heat_coupling*heat_level
                          for j in range(TRIALS)))
        t = _tail_time(i)
        p_level = max(p_level, abs(p)+abs(primary.offset_newtons)
                      + abs(primary.drift_newtons_per_second)*t
                      + primary.vibration_newtons)
        r_level = max(r_level, abs(r)+abs(reference.offset_newtons)
                      + abs(reference.drift_newtons_per_second)*t
                      + reference.vibration_newtons)
    return p_level, r_level


def base_parts(config, order, corner, heat_centre):
    """Deterministic contrast, heat and force coefficients of one order."""
    primary, reference = channels(config)
    gp, gr, w = corner
    gm, hm = _coefficients(primary)
    gr_m, hr_m = _coefficients(reference)
    coupling = config["reference_common_coupling"]
    heat_coupling = config["reference_heat_coupling"]
    c_heat = [0.0]*TRIALS
    c_force = [0.0]*TRIALS
    c_ref_force = [0.0]*TRIALS
    base = 0.0
    for i, sigma in enumerate(order):
        t = _tail_time(i)
        for j in range(TRIALS):
            c_heat[j] += sigma*((1+gp)*hm[i][j]
                                - w*(1+gr)*heat_coupling*hr_m[i][j])/4
            c_force[j] += sigma*(1+gp)*gm[i][j]/4
            c_ref_force[j] += -sigma*w*(1+gr)*gr_m[i][j]/4
        base += sigma*(
            (1+gp)*sum(gm[i][j]*COMMON for j in range(TRIALS))
            - w*(1+gr)*sum(gr_m[i][j]*coupling*COMMON for j in range(TRIALS))
            + primary.offset_newtons-w*reference.offset_newtons
            + (primary.drift_newtons_per_second
               - w*reference.drift_newtons_per_second)*t)/4
    base += sum(c_heat)*heat_centre
    return base, c_heat, c_force, c_ref_force


def design(config):
    """Worst-case budget, tiers and margins for one configuration."""
    primary, reference = channels(config)
    window = optical_window(config["phase_jitter_radians"],
                            config["feed_variation_fraction"])
    box = transfer_box(config)
    heat_centre = (window["heat_minimum_watts"]+window["heat_maximum_watts"])/2
    heat_radius = (window["heat_maximum_watts"]-window["heat_minimum_watts"])/2
    s_g, s_w = stationarity(config)
    leak = config["leakage"]
    dl = config["leakage_knowledge"]
    base_max, heat_max, rho = 0.0, 0.0, 0.0
    witness = {}
    for order in ORDERS:
        for corner in _corners(config):
            base, c_heat, c_force, c_ref = base_parts(config, order, corner,
                                                      heat_centre)
            gp, gr, w = corner
            heat_sum = math.fsum(abs(c) for c in c_heat)*heat_radius
            base_max = max(base_max, abs(base))
            heat_max = max(heat_max, heat_sum)
            for sign in (1, -1):
                score = sign*base+heat_sum
                if sign not in witness or score > witness[sign][0]:
                    witness[sign] = (score, order, corner)
            for l in (max(0.0, leak-dl), leak+dl):
                transfer = (1+gp)-w*l*(1+gr)
                deviation = math.fsum(
                    abs(c_force[j]+l*c_ref[j]-transfer*order[j]/4)
                    for j in range(TRIALS))/2
                rho = max(rho, deviation)
    gp_max = PRIMARY.calibration_fraction+config["calibration_knowledge"]
    gr_max = REFERENCE.calibration_fraction+config["calibration_knowledge"]
    p_level, r_level = _levels(config, primary, reference, gp_max, gr_max,
                               COMMON, 0.0, window["heat_maximum_watts"])
    noise = noise_term(config)
    vibration = vibration_term(config)
    gain = gain_term(config, p_level, r_level)
    allowance = 2*STRUCTURAL*config["structural_allowance_scale"]
    envelope = base_max+heat_max+noise+gain+vibration
    lower = box[0]*(window["optical_minimum_newtons"]-window["walk_newtons"])
    upper = box[1]*(window["optical_maximum_newtons"]+window["walk_newtons"])
    tier_a = 2*(primary.noise_bound_newtons
                + abs(WEIGHT)*reference.noise_bound_newtons
                + config["weight_knowledge"]*r_level
                + config["transfer_uncertainty"]*p_level
                + STRUCTURAL*config["structural_allowance_scale"]
                + config["phase_force_sensitivity_newtons_per_radian"]
                * config["phase_jitter_radians"])
    tier_b = envelope+allowance
    s_max = window["signal_maximum_newtons"]
    s_min = window["signal_minimum_newtons"]
    p_signal = p_level+s_max/2
    r_signal = r_level+(leak+dl)*s_max/2
    gain_signal = gain_term(config, p_signal, r_signal)
    signal_error = (base_max+heat_max+noise+vibration+gain_signal+rho*s_max)
    tier_a_signal = tier_a+2*(config["weight_knowledge"]*(r_signal-r_level)
                              + config["transfer_uncertainty"]*(p_signal-p_level))
    tier_b_signal = (noise+gain_signal+base_max+heat_max+vibration+allowance
                     + rho*(box[1]*s_max+noise)/box[0])
    transferred = box[0]*s_min
    return {
        "transfer_box": box,
        "window": window,
        "terms_newtons": {
            "base": base_max, "heat": heat_max, "noise": noise, "gain": gain,
            "vibration": vibration, "structural": allowance,
        },
        "signal_transient_fraction": rho,
        "primary_level_newtons": p_level,
        "reference_level_newtons": r_level,
        "envelope_newtons": envelope,
        "signal_envelope_newtons": signal_error,
        "lower_newtons": lower,
        "upper_newtons": upper,
        "tiers": {
            "A": {"bound_newtons": tier_a,
                  "null_margin_newtons": lower-envelope-tier_a,
                  "signal_margin_newtons":
                      transferred-signal_error-tier_a_signal},
            "B": {"bound_newtons": tier_b,
                  "null_margin_newtons": lower-envelope-tier_b,
                  "signal_margin_newtons":
                      transferred-signal_error-tier_b_signal},
        },
        "_witness": witness,
        "_heat_centre": heat_centre,
        "_heat_radius": heat_radius,
    }


def public_design(result):
    return {key: value for key, value in result.items()
            if not key.startswith("_")}


def _stream(*parts):
    text = "|".join(str(part) for part in parts).encode("ascii")
    return int.from_bytes(hashlib.sha256(text).digest()[:8], "big")


def bounds(rows, config, plan, contrast):
    """Tier A and tier B half-widths from observed tails only."""
    primary, reference = channels(config)
    p_obs = max(abs(row["primary_tail_newtons"]) for row in rows)
    r_obs = max(abs(row["reference_tail_newtons"]) for row in rows)
    tier_a = 2*(primary.noise_bound_newtons
                + abs(WEIGHT)*reference.noise_bound_newtons
                + config["weight_knowledge"]*r_obs
                + config["transfer_uncertainty"]*p_obs
                + STRUCTURAL*config["structural_allowance_scale"]
                + config["phase_force_sensitivity_newtons_per_radian"]
                * config["phase_jitter_radians"])
    terms = plan["terms_newtons"]
    noise = terms["noise"]
    tier_b = (noise+gain_term(config, p_obs, r_obs)+terms["base"]
              + terms["heat"]+terms["vibration"]+terms["structural"]
              + plan["signal_transient_fraction"]*(abs(contrast)+noise)
              / plan["transfer_box"][0])
    guard = 64*math.ulp(max(abs(contrast), tier_a, tier_b))+GUARD
    return tier_a+guard, tier_b+guard


def contrast_of(rows):
    if (sum(row["label"] == "A" for row in rows) != TRIALS//2
            or sum(row["label"] == "B" for row in rows) != TRIALS//2):
        raise ValueError("expected four complete A/B pairs")
    return (math.fsum(r["difference_tail_newtons"] for r in rows
                      if r["label"] == "B")
            - math.fsum(r["difference_tail_newtons"] for r in rows
                        if r["label"] == "A"))/(TRIALS//2)


def optical_contrast(rows):
    low = (math.fsum(r["optical_interval_newtons"][0] for r in rows
                     if r["label"] == "B")
           - math.fsum(r["optical_interval_newtons"][1] for r in rows
                       if r["label"] == "A"))/(TRIALS//2)
    high = (math.fsum(r["optical_interval_newtons"][1] for r in rows
                      if r["label"] == "B")
            - math.fsum(r["optical_interval_newtons"][0] for r in rows
                        if r["label"] == "A"))/(TRIALS//2)
    return [low, high]


def judge(contrast, half, predicted):
    low, high = contrast-half, contrast+half
    resolved = low > 0 or high < 0
    overlap = max(low, predicted[0]) <= min(high, predicted[1])
    return resolved, overlap


_optical_cache = {}


def _optical_plan(stream, null, phase_jitter, feed_variation):
    key = (stream, null, phase_jitter, feed_variation)
    if key not in _optical_cache:
        dummy = Balance(1.0, 1.0, 0, 0, 0, 0, 0, 0, 0)
        public, truth = acquire_optical(
            dummy, stream, **SOURCE, pairs=TRIALS//2, samples_per_trial=SAMPLES,
            step_seconds=STEP, phase_jitter_bound_radians=phase_jitter,
            feed_variation_bound_fraction=feed_variation,
            disclose_trial_sources=True, null=null)
        _optical_cache[key] = [
            (trial["label"], item["source"]["phase_radians"],
             item["source"]["optical_feed_power_watts"]
             / SOURCE["optical_feed_watts"],
             item["start_seconds"]+SAMPLES*STEP)
            for trial, item in zip(public["trials"], truth["source_trials"])]
    return _optical_cache[key]


def _phase_lock(phase):
    """Source-frame sign of the recoil at this phase; label independent."""
    if phase == 0:
        return 0
    return 1 if recoil(math.copysign(QUARTER, phase), 1) > 0 else -1


def run_trials(config, plan_rows, control, orientation, constants, *,
               vibration_hertz, seed_stream):
    """Acquire through the committed channels, one call per trial.

    Each plan row is (label, phase, feed, end, psi, xi, u_p, u_r, v, mode).
    Gains and weight are replaced per trial; state continues explicitly.
    """
    primary, reference = channels(config)
    gp, gr, w, leak = constants
    continuation = None
    rows, signal = [], {"A": 0.0, "B": 0.0}
    rng = random.Random(seed_stream)
    impostor = nominal_contrast()/2
    for index, row in enumerate(plan_rows, 1):
        label, phase, feed, end, psi, xi, u_p, u_r, v, mode = row
        recoil_force = recoil(phase+psi, feed*(1+xi))
        power = heat(phase+psi, feed*(1+xi))
        lock = _phase_lock(phase)
        if control in ("opposite-phase", "phase-null"):
            force = orientation*recoil_force
        elif control == "force-decoupled":
            force = 0.0
        elif control == "impostor-lab-fixed-in-window":
            force = lock*impostor
        elif control == "impostor-source-fixed-in-window":
            force = orientation*lock*impostor
        elif control == "impostor-out-of-window":
            force = lock*OUT_OF_WINDOW
        else:
            raise ValueError("unsupported control")
        signal[label] += force/(TRIALS//2)
        p = replace(primary, calibration_fraction=gp+u_p,
                    vibration_hertz=vibration_hertz)
        r = replace(reference, calibration_fraction=gr+u_r,
                    vibration_hertz=vibration_hertz)
        result = acquire_channels(
            p, r, [force]*SAMPLES, [COMMON]*SAMPLES, [power]*SAMPLES, STEP,
            rng.randrange(2**32), weight=w+v, leakage=leak,
            reference_common_coupling=config["reference_common_coupling"],
            reference_heat_coupling=config["reference_heat_coupling"],
            noise_mode=mode, initial=continuation)
        continuation = result["continuation"]
        optical = detector_interval(
            phase, feed*SOURCE["optical_feed_watts"]*_unit(phase)[0], end)
        if orientation == -1:
            optical = [-optical[1], -optical[0]]
        rows.append({
            "trial_id": f"T{index:03d}", "label": label,
            "primary_tail_newtons":
                tail_mean(result["primary_readings_newtons"], TAIL),
            "reference_tail_newtons":
                tail_mean(result["reference_readings_newtons"], TAIL),
            "difference_tail_newtons":
                tail_mean(result["difference_readings_newtons"], TAIL),
            "optical_interval_newtons": optical,
        })
    return rows, signal["B"]-signal["A"]


def assess(rows, injected, config, plan, constants):
    """Interval outcome for both tiers from readings; truth only audits."""
    gp, gr, w, leak = constants
    contrast = contrast_of(rows)
    raw = optical_contrast(rows)
    walk = plan["window"]["walk_newtons"]
    predicted = map_interval([raw[0]-walk, raw[1]+walk], plan["transfer_box"])
    half_a, half_b = bounds(rows, config, plan, contrast)
    actual = (1+gp)-w*leak*(1+gr)
    truth = actual*injected
    out = {
        "contrast_newtons": contrast,
        "optical_raw_newtons": raw,
        "predicted_newtons": predicted,
        "truth_newtons": truth,
        "tiers": {},
    }
    for tier, half in (("A", half_a), ("B", half_b)):
        resolved, overlap = judge(contrast, half, predicted)
        out["tiers"][tier] = {
            "half_newtons": half, "resolved": resolved, "overlap": overlap,
            "truth": abs(contrast-truth) <= half,
        }
    return out


SINGLE = {
    "opposite-phase": (True, True),
    "phase-null": (False, True),
    "force-decoupled": (False, False),
    "impostor-lab-fixed-in-window": (True, True),
    "impostor-source-fixed-in-window": (True, True),
    "impostor-out-of-window": (True, False),
}
MIMIC = {"impostor-lab-fixed-in-window", "impostor-source-fixed-in-window"}


def single_expectation(control, orientation):
    """Amendment 2: a lab-fixed force cannot follow the reversed prediction."""
    if control == "impostor-lab-fixed-in-window" and orientation == -1:
        return (True, False)
    return SINGLE[control]


def _aligned(interval):
    if interval[0] > 0:
        return 1, interval
    if interval[1] < 0:
        return -1, [-interval[1], -interval[0]]
    return 1, interval


def dual(plus, minus, plan, tier):
    """Source-frame difference D and lab-frame sum Sigma; no averaging credit."""
    sign_p, optical_p = _aligned(plus["optical_raw_newtons"])
    sign_m, optical_m = _aligned(
        [-minus["optical_raw_newtons"][1], -minus["optical_raw_newtons"][0]])
    k_p = sign_p*plus["contrast_newtons"]
    k_m = sign_m*minus["contrast_newtons"]
    half = (plus["tiers"][tier]["half_newtons"]
            + minus["tiers"][tier]["half_newtons"])/2
    box = plan["transfer_box"]
    walk = plan["window"]["walk_newtons"]
    raw = [(optical_p[0]+optical_m[0])/2-walk,
           (optical_p[1]+optical_m[1])/2+walk]
    predicted = map_interval(raw, [box[0]-FLIP, box[1]+FLIP])
    difference, total = (k_p-k_m)/2, (k_p+k_m)/2
    resolved, overlap = judge(difference, half, predicted)
    sigma_half = half+FLIP*max(abs(predicted[0]), abs(predicted[1]))
    sigma_resolved = abs(total) > sigma_half
    truth_d = (sign_p*plus["truth_newtons"]-sign_m*minus["truth_newtons"])/2
    truth_s = (sign_p*plus["truth_newtons"]+sign_m*minus["truth_newtons"])/2
    return {
        "difference_newtons": difference, "sum_newtons": total,
        "half_newtons": half, "sigma_half_newtons": sigma_half,
        "resolved": resolved, "overlap": overlap,
        "sigma_resolved": sigma_resolved,
        "truth": (abs(difference-truth_d) <= half
                  and abs(total-truth_s) <= sigma_half),
    }


DUAL = {
    "opposite-phase": (True, True, False),
    "phase-null": (False, True, False),
    "force-decoupled": (False, False, False),
    "impostor-lab-fixed-in-window": (False, False, True),
    "impostor-source-fixed-in-window": (True, True, False),
}


def seeded_plan(config, seed, stream, null, rng):
    s_g, s_w = stationarity(config)
    jitter = config["phase_jitter_radians"]
    variation = config["feed_variation_fraction"]
    rows = []
    for label, phase, feed, end in _optical_plan(stream, null, jitter,
                                                 variation):
        rows.append((label, phase, feed, end,
                     rng.uniform(-jitter, jitter),
                     rng.uniform(-variation, variation),
                     rng.uniform(-s_g, s_g), rng.uniform(-s_g, s_g),
                     rng.uniform(-s_w, s_w), "random"))
    return rows


def seeded_acquisition(name, config, plan, seed, control, orientation):
    rng = random.Random(_stream("study", name, seed, control, orientation))
    stream = _stream("optical", seed, orientation, control == "phase-null")%2**32
    dg = config["calibration_knowledge"]
    dw = config["weight_knowledge"]
    dl = config["leakage_knowledge"]
    constants = (
        PRIMARY.calibration_fraction+rng.uniform(-dg, dg),
        REFERENCE.calibration_fraction+rng.uniform(-dg, dg),
        WEIGHT+rng.uniform(-dw, dw),
        max(0.0, config["leakage"]+rng.uniform(-dl, dl)))
    hertz = rng.uniform(BAND[0], BAND[1])
    plan_rows = seeded_plan(config, seed, stream, control == "phase-null", rng)
    rows, injected = run_trials(config, plan_rows, control, orientation,
                                constants, vibration_hertz=hertz,
                                seed_stream=rng.randrange(2**32))
    return assess(rows, injected, config, plan, constants)


def _extreme(base, config, key):
    """Lattice phase, feed and walk choices for a witness trial."""
    jitter = config["phase_jitter_radians"]
    variation = config["feed_variation_fraction"]
    phases = _lattice(base, jitter, PHASE_POINTS)
    feeds = _lattice(1.0, variation, FEED_POINTS)
    walks = (-jitter, 0.0, jitter) if jitter else (0.0,)
    drifts = (-variation, 0.0, variation) if variation else (0.0,)
    return max(product(phases, feeds, walks, drifts), key=key)


def witness(name, config, plan, kind, sign):
    """Adversarial acquisition from the sign of the engine coefficients.

    kind 'null' attacks a force-decoupled control toward sign*E. Kind 'signal'
    attacks opposite-phase away from truth to shrink its contrast.
    """
    control = "force-decoupled" if kind == "null" else "opposite-phase"
    positive = QUARTER if recoil(QUARTER, 1) > 0 else -QUARTER
    s_g, s_w = stationarity(config)
    if kind == "null":
        direction = sign
        _, order, corner = plan["_witness"][direction]
        mapping = {1: -positive, -1: positive}
    else:
        mapping = {1: positive, -1: -positive} if sign > 0 else {
            1: -positive, -1: positive}
        direction = -sign
        _, order, corner = plan["_witness"][direction]
    _, c_heat, _, _ = base_parts(config, order, corner, plan["_heat_centre"])
    plan_rows = []
    for i, sigma in enumerate(order):
        base = mapping[sigma]
        if kind == "null":
            up = direction*c_heat[i] >= 0
            choice = _extreme(base, config, lambda c: (
                heat(c[0]+c[2], c[1]*(1+c[3])) if up
                else -heat(c[0]+c[2], c[1]*(1+c[3]))))
        else:
            aligned = 1 if recoil(base, 1) > 0 else -1
            choice = _extreme(base, config, lambda c: (
                -aligned*recoil(c[0]+c[2], c[1]*(1+c[3]))))
        phase, feed, psi, xi = choice
        push = direction*sigma
        plan_rows.append((
            "B" if sigma == 1 else "A", phase, feed, (i+1)*SAMPLES*STEP,
            psi, xi, push*s_g, -push*s_g, -push*s_w,
            "positive-extreme" if push > 0 else "negative-extreme"))
    leak = config["leakage"]
    constants = (*corner, leak)
    rows, injected = run_trials(
        config, plan_rows, control, 1, constants, vibration_hertz=BAND[0],
        seed_stream=_stream("witness", name, kind, sign)%2**32)
    outcome = assess(rows, injected, config, plan, constants)
    error = abs(outcome["contrast_newtons"]-outcome["truth_newtons"])
    limit = (plan["envelope_newtons"] if kind == "null"
             else plan["signal_envelope_newtons"])
    outcome["kind"] = kind
    outcome["sign"] = sign
    outcome["error_newtons"] = error
    outcome["envelope_limit_newtons"] = limit
    outcome["attainment_fraction"] = error/limit
    outcome["within_envelope"] = error <= limit+GUARD
    return outcome


def _row(seed, control, orientation, result):
    return {
        "seed": seed, "control": control, "orientation": orientation,
        "contrast_newtons": result["contrast_newtons"],
        "truth_newtons": result["truth_newtons"],
        "optical_raw_newtons": result["optical_raw_newtons"],
        "predicted_newtons": result["predicted_newtons"],
        "half_a_newtons": result["tiers"]["A"]["half_newtons"],
        "half_b_newtons": result["tiers"]["B"]["half_newtons"],
    }


def cohort(name, config, seeds, keep_rows=True):
    plan = design(config)
    rows = []
    totals = {
        tier: {"single_matched": 0, "single_total": 0, "dual_matched": 0,
               "dual_total": 0, "lab_detected": 0, "lab_total": 0,
               "truth_contained": 0, "truth_total": 0,
               "mimic_matched": 0, "mimic_total": 0,
               "single_by_control": {}, "dual_by_control": {}}
        for tier in ("A", "B")}

    def single(tier, control, orientation, result):
        entry = result["tiers"][tier]
        state = totals[tier]
        matched = ((entry["resolved"], entry["overlap"])
                   == single_expectation(control, orientation))
        if control in MIMIC:
            state["mimic_total"] += 1
            state["mimic_matched"] += matched
        else:
            state["single_total"] += 1
            state["single_matched"] += matched
            bucket = state["single_by_control"].setdefault(control, [0, 0])
            bucket[0] += matched
            bucket[1] += 1
        state["truth_total"] += 1
        state["truth_contained"] += entry["truth"]

    for seed in seeds:
        for control in CONTROLS:
            plus = seeded_acquisition(name, config, plan, seed, control, 1)
            minus = seeded_acquisition(name, config, plan, seed, control, -1)
            rows.append(_row(seed, control, 1, plus))
            rows.append(_row(seed, control, -1, minus))
            for tier in ("A", "B"):
                single(tier, control, 1, plus)
                single(tier, control, -1, minus)
                pair = dual(plus, minus, plan, tier)
                state = totals[tier]
                matched = ((pair["resolved"], pair["overlap"],
                            pair["sigma_resolved"]) == DUAL[control])
                state["truth_total"] += 1
                state["truth_contained"] += pair["truth"]
                if control == "impostor-source-fixed-in-window":
                    state["mimic_total"] += 1
                    state["mimic_matched"] += matched
                else:
                    state["dual_total"] += 1
                    state["dual_matched"] += matched
                    bucket = state["dual_by_control"].setdefault(control, [0, 0])
                    bucket[0] += matched
                    bucket[1] += 1
                if control == "impostor-lab-fixed-in-window":
                    state["lab_total"] += 1
                    state["lab_detected"] += matched
        control = "impostor-out-of-window"
        result = seeded_acquisition(name, config, plan, seed, control, 1)
        rows.append(_row(seed, control, 1, result))
        for tier in ("A", "B"):
            single(tier, control, 1, result)
    witnesses = [witness(name, config, plan, kind, sign)
                 for kind in ("null", "signal") for sign in (1, -1)]
    classes = {tier: classify(plan, totals[tier], witnesses, tier)
               for tier in ("A", "B")}
    return {
        "name": name,
        "design": public_design(plan),
        "seeded": totals,
        "witnesses": witnesses,
        "outcome": classes,
        **({"rows": rows} if keep_rows else {}),
    }


def classify(plan, totals, witnesses, tier):
    """Section 8 outcome classes, in their declared priority order."""
    margins = plan["tiers"][tier]
    valid = (all(item["within_envelope"] for item in witnesses)
             and totals["mimic_matched"] == totals["mimic_total"])
    margin = (margins["null_margin_newtons"] >= REQUIRED
              and margins["signal_margin_newtons"] >= REQUIRED)
    seeded = (totals["single_matched"] == totals["single_total"]
              and totals["dual_matched"] == totals["dual_total"]
              and totals["lab_detected"] == totals["lab_total"]
              and totals["truth_contained"] == totals["truth_total"])
    witness_truth = all(item["tiers"][tier]["truth"] for item in witnesses)
    rejected = all(
        not item["tiers"][tier]["resolved"]
        and not item["tiers"][tier]["overlap"]
        for item in witnesses if item["kind"] == "null")
    if not valid:
        return "inconclusive_invalid_envelope"
    if margin and seeded and witness_truth and rejected:
        return "robust_margin_positive_conditional"
    if seeded and witness_truth:
        return "seeded_pass_not_robust"
    return "negative"


def provenance():
    return {name: _digest(name) for name in IMPLEMENTATION}


def _margins(config):
    plan = design(config)
    return {
        "envelope_newtons": plan["envelope_newtons"],
        "lower_newtons": plan["lower_newtons"],
        "tiers": plan["tiers"],
    }


def _meets(config):
    tier = design(config)["tiers"]["B"]
    return (tier["null_margin_newtons"] >= REQUIRED
            and tier["signal_margin_newtons"] >= REQUIRED)


SWEEP_KEYS = {
    "read_noise_scale": "read_noise_scale",
    "structural_allowance_scale": "structural_allowance_scale",
}


def sweep(start):
    rows = {}
    for key, values in PROTOCOL["exploratory"]["sweeps"].items():
        rows[key] = [{"value": value,
                      **_margins(configuration(start, **{key: value}))}
                     for value in values]
    return rows


def thresholds(start):
    """Exploratory bracket of the largest tolerated value, tier B."""
    steps = PROTOCOL["exploratory"]["threshold_bisection_steps"]
    results = {}
    sweeps = PROTOCOL["exploratory"]["sweeps"]
    for key in ("leakage", "reference_response_seconds",
                "reference_heat_coupling", "read_noise_scale",
                "weight_stationarity", "gain_stationarity",
                "structural_allowance_scale"):
        values = sorted(sweeps[key])
        passing = [v for v in values if _meets(configuration(start, **{key: v}))]
        if not passing:
            results[key] = {"state": "no_lattice_value_meets_requirement"}
            continue
        low = max(passing)
        above = [v for v in values if v > low]
        if not above:
            results[key] = {"state": "entire_range_meets_requirement",
                            "largest_value": low}
            continue
        high = min(above)
        for _ in range(steps):
            middle = (low+high)/2
            if _meets(configuration(start, **{key: middle})):
                low = middle
            else:
                high = middle
        results[key] = {"state": "bracketed", "largest_value": low,
                        "failing_value": high}
    return results


def factorial():
    names = tuple(FACTORS)
    rows = []
    for mask in range(2**len(names)):
        chosen = tuple(n for i, n in enumerate(names) if mask >> i & 1)
        plan = design(configuration(chosen))
        rows.append({
            "factors": list(chosen),
            "tier_a_null_newtons": plan["tiers"]["A"]["null_margin_newtons"],
            "tier_a_signal_newtons":
                plan["tiers"]["A"]["signal_margin_newtons"],
            "tier_b_null_newtons": plan["tiers"]["B"]["null_margin_newtons"],
            "tier_b_signal_newtons":
                plan["tiers"]["B"]["signal_margin_newtons"],
        })
    return rows


def _preamble(kind):
    return {
        "study": PROTOCOL["study"],
        "kind": kind,
        "status": "virtual_lab_simulated_experiment_not_physical_evidence",
        "label": "Virtual lab - simulated experiment",
        "implementation": provenance(),
        "warning": "Virtual lab only. Levels are assumed. The channel envelope "
                   "is exact only inside the declared model and box; the "
                   "optical window is numerical. No measured calibration, "
                   "hardware twin or physical recoil is established.",
    }


def exploratory():
    names = tuple(FACTORS)
    seeds = PROTOCOL["exploratory"]["seeds"]
    span = list(range(seeds[0], seeds[1]+1))
    return {
        **_preamble("exploratory_sensitivity_not_confirmatory"),
        "sweeps": {"from_baseline": sweep(()), "from_all": sweep(names)},
        "thresholds_from_all": thresholds(names),
        "factorial": factorial(),
        "pilot": [cohort(name, configuration(factors), span, keep_rows=False)
                  for name, factors in (("baseline", ()), ("all", names))],
    }


def confirmatory():
    seeds = PROTOCOL["confirmatory"]["seeds"]
    span = list(range(seeds[0], seeds[1]+1))
    rows = [cohort(name, configuration(factors), span)
            for name, factors in named_configurations()]
    return {
        **_preamble("predeclared_confirmatory_validation"),
        "nominal_contrast_newtons": nominal_contrast(),
        "required_margin_newtons": REQUIRED,
        "configurations": rows,
        "outcomes": {row["name"]: row["outcome"] for row in rows},
    }


def main():
    arguments = sys.argv[1:]
    if arguments == ["exploratory"]:
        result = exploratory()
    elif arguments == ["confirmatory"]:
        result = confirmatory()
    else:
        raise SystemExit("usage: pf002_mechanistic_robustness_v1.py "
                         "exploratory|confirmatory")
    payload = json.dumps(result, sort_keys=True, separators=(",", ":"),
                         allow_nan=False)
    limit = PROTOCOL["limits"]["maximum_retained_bytes"]
    if len(payload.encode("utf-8")) > limit:
        raise SystemExit("study output exceeds the declared limit")
    print(payload)


if __name__ == "__main__":
    main()
