"""Coupled synthetic acquisition; no canonical or causal result assignment."""

import math
import json
import sys

from virtual_acquisition import acquire as acquire_balance, analyse as analyse_balance
from trial_detector import acquire_trial, analyse_trial
from virtual_instruments import Balance
from recoil_budget import bounded


def apparatus_bound(balance):
    """Predeclared bound, independent of source injections and phase labels.

    Eight ten-second trials, last ten 0.1-second samples analysed. Source
    feed <=1.01 W, efficiency 0.25, control 0.1 W; total heat <4.2 W.
    Source recoil plus permitted correlated force <=5 nN. Thermal response
    starts cold and never exceeds its constant maximum target. Constant
    offsets are conservatively included, not assumed to cancel.
    """
    balance.validate()
    thermal = 4.2*abs(balance.thermal_newtons_per_watt)
    maximum_target = 5e-9+thermal
    settling = 2*maximum_target*math.exp(-9.1/balance.response_seconds)
    per_trial = (thermal+settling+abs(balance.calibration_fraction)*maximum_target
                 +abs(balance.offset_newtons)+80*abs(balance.drift_newtons_per_second)
                 +balance.vibration_newtons+balance.noise_bound_newtons)
    return 2*per_trial


def acquire(balance, seed, *, null=False, signal_enabled=True, orientation=1,
            phase_correlated_force_newtons=0, cone_degrees=2,
            pointing_bound_degrees=0.01, grid=(8, 32), gain_bound=0.0001,
            total_power_bound_watts=0.0001, additive_error_watts=1e-5,
            gain_drift_per_second=1e-6,
            power_drift_watts_per_second=1e-6, wavelength_m=1.55e-6,
            aperture_radius_m=31e-6, separation_m=31e-6,
            optical_feed_watts=1.0, laser_conversion_efficiency=0.25,
            control_power_watts=0.1, phase_jitter_bound_radians=0.01,
            feed_variation_bound_fraction=0.01):
    """Fixed eight-trial, 80-second sequence with finite optical readout.

    The source-disabled control disables force coupling, not illumination or
    heating: it tests synthetic readout attribution, not a physical laser-off
    condition. Optical calibration bounds are illustrative design inputs.
    Detector geometry and calibration defaults preserve the earlier coupled
    campaign; callers may declare a different finite detector for a sweep.
    """
    bounded(phase_correlated_force_newtons, -1e-9, 1e-9, "coupled correlated force")
    for value, expected, name in ((optical_feed_watts, 1.0, "optical feed"),
                                  (laser_conversion_efficiency, 0.25, "conversion efficiency"),
                                  (control_power_watts, 0.1, "control power")):
        if bounded(value, expected, expected, name) != expected:
            raise ValueError("source power outside qualified apparatus envelope")
    observations, truth = acquire_balance(balance, seed, null=null,
        signal_enabled=signal_enabled, orientation=orientation,
        phase_correlated_force_newtons=phase_correlated_force_newtons,
        phase_jitter_bound_radians=phase_jitter_bound_radians,
        feed_variation_bound_fraction=feed_variation_bound_fraction,
        disclose_trial_sources=True, wavelength_m=wavelength_m,
        aperture_radius_m=aperture_radius_m, separation_m=separation_m,
        optical_feed_watts=optical_feed_watts,
        laser_conversion_efficiency=laser_conversion_efficiency,
        control_power_watts=control_power_watts)
    detectors, disclosures = [], []
    for trial in truth["source_trials"]:
        source = trial["source"]
        detector, disclosure = acquire_trial(
            phase_radians=source["phase_radians"],
            escaping_power_watts=source["escaping_radiated_power_watts"],
            end_seconds=trial["start_seconds"]+10,
            gain_drift_per_second=gain_drift_per_second,
            power_drift_watts_per_second=power_drift_watts_per_second,
            additive_error_watts=additive_error_watts,
            grid=grid, cone_degrees=cone_degrees,
            pointing_bound_degrees=pointing_bound_degrees,
            gain_bound=gain_bound,
            total_power_bound_watts=total_power_bound_watts,
            wavelength_m=wavelength_m, aperture_radius_m=aperture_radius_m,
            separation_m=separation_m)
        detectors.append({"trial_id": trial["trial_id"], "reading": detector})
        disclosures.append(disclosure)
    return {"balance": observations, "detectors": detectors,
            "orientation": orientation}, {"balance": truth, "detectors": disclosures}


def analyse(public, *, differential_error_bound_newtons):
    """Compare blind balance and optical intervals, without accessing truth.

    Apparatus error is externally supplied and must cover every nuisance.
    Interval agreement is consistency only, never proof of a mechanism.
    """
    if type(public) is not dict or set(public) != {"balance", "detectors", "orientation"}:
        raise ValueError("expected public coupled acquisition only")
    orientation = public["orientation"]
    if type(orientation) is not int or orientation not in (-1, 1):
        raise ValueError("invalid declared orientation")
    measured = analyse_balance(public["balance"], tail_samples=10,
        differential_error_bound_newtons=differential_error_bound_newtons)
    trials = public["balance"]["trials"]
    detectors = public["detectors"]
    if type(detectors) is not list or len(detectors) != len(trials):
        raise ValueError("missing or excess trial detector records")
    intervals = {"A": [], "B": []}
    for trial, detector in zip(trials, detectors):
        if (type(detector) is not dict or set(detector) != {"trial_id", "reading"}
                or detector["trial_id"] != trial["trial_id"]):
            raise ValueError("misaligned detector trial")
        low, high = analyse_trial(detector["reading"])
        intervals[trial["label"]].append((low, high) if orientation == 1 else (-high, -low))
    # Equal complete pairs are enforced by the balance analyser. Bounds do
    # not shrink with repeated trials; endpoint means retain shared errors.
    a, b = intervals["A"], intervals["B"]
    predicted = [math.fsum(i[0] for i in b)/len(b)-math.fsum(i[1] for i in a)/len(a),
                 math.fsum(i[1] for i in b)/len(b)-math.fsum(i[0] for i in a)/len(a)]
    guard = 64*math.ulp(max(abs(value) for value in predicted))
    predicted = [predicted[0]-guard, predicted[1]+guard]
    observed = measured["contrast_interval_newtons"]
    return {"status": "synthetic_interval_consistency_not_causal_evidence",
            "balance": measured, "optical_contrast_interval_newtons": predicted,
            "intervals_overlap": max(observed[0], predicted[0]) <= min(observed[1], predicted[1]),
            "warning": "Supplied apparatus bounds; overlap cannot establish physical recoil or exclude an impostor."}


def main():
    if len(sys.argv) != 1:
        raise SystemExit("Fixed coupled campaign accepts no arguments")
    balance = Balance(0.1, 2, 0, 0, 0, 0, 0, 0, 1e-13)
    cases = (("opposite-phase", {}), ("phase-null", {"null": True}),
             ("force-decoupled", {"signal_enabled": False}),
             ("orientation-reversed", {"orientation": -1}),
             ("impostor", {"signal_enabled": False,
                           "phase_correlated_force_newtons": 1e-9}))
    rows = []
    for name, options in cases:
        public, _ = acquire(balance, 42, **options)
        rows.append({"case": name, **analyse(public,
                    differential_error_bound_newtons=apparatus_bound(balance))})
    output = json.dumps({"status": "synthetic_coupled_campaign_not_physical_evidence",
                         "rows": rows, "limits": {"trials": 40, "balance_samples": 4000,
                         "detector_pixels": 10240, "output_bytes": 32768}}, allow_nan=False)
    if len(output.encode()) > 32768:
        raise SystemExit("coupled campaign output exceeds 32 KiB")
    print(output)


if __name__ == "__main__":
    main()
