"""Bounded synthetic phase trials; hidden truth is not an analysis input."""

import math
import random

from optical_driver import predict
from recoil_budget import bounded
from virtual_instruments import Balance, observe


def acquire(balance: Balance, seed: int, *, pairs=4, samples_per_trial=100,
            step_seconds=0.1, signal_enabled=True, null=False,
            phase_correlated_force_newtons=0, phase_jitter_bound_radians=0,
            feed_variation_bound_fraction=0, orientation=1,
            disclose_trial_sources=False, 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) -> tuple[dict, dict]:
    """Return separate anonymised observations and later-disclosed truth.

    Fixed candidate geometry and power are hypothetical, not an equipment
    prescription. The first trial starts cold; response and thermal state,
    drift time and vibration phase continue across subsequent trials.
    """
    if type(seed) is not int or not 0 <= seed <= 2**32-1:
        raise ValueError("seed must be an unsigned 32-bit integer")
    if type(pairs) is not int or not 2 <= pairs <= 16:
        raise ValueError("pairs must be an integer from 2 to 16")
    if type(samples_per_trial) is not int or not 10 <= samples_per_trial <= 128:
        raise ValueError("trial sample count must be an integer from 10 to 128")
    if type(signal_enabled) is not bool or type(null) is not bool:
        raise ValueError("signal and null controls must be booleans")
    if type(disclose_trial_sources) is not bool:
        raise ValueError("trial source disclosure must be boolean")
    bounded(step_seconds, 0.001, 10, "sample step")
    if pairs*2*samples_per_trial*step_seconds > 3600:
        raise ValueError("complete campaign exceeds one hour")
    artefact = bounded(phase_correlated_force_newtons, -1e-6, 1e-6, "correlated force")
    phase_jitter = bounded(phase_jitter_bound_radians, 0, 0.1, "phase jitter bound")
    feed_variation = bounded(feed_variation_bound_fraction, 0, 0.1, "feed variation bound")
    if type(orientation) is not int or orientation not in (-1, 1):
        raise ValueError("orientation must be signed unit integer")
    balance.validate()
    rng = random.Random(seed)
    # Independent injection stream preserves the existing trial/noise sequence.
    source_rng = random.Random(seed ^ 0x51A7C3)
    phases = [math.pi/2, -math.pi/2]
    if null:
        phases = [0, 0]
    if rng.getrandbits(1):
        phases.reverse()
    labels = ("A", "B")

    def source_at(phase, feed):
        return predict(wavelength_m, aperture_radius_m, separation_m, phase,
                       feed, laser_conversion_efficiency, control_power_watts)

    sources = [source_at(phase, optical_feed_watts) for phase in phases]
    trials = []
    order = []
    source_trials = []
    continuation = {"mechanical_newtons": 0, "thermal_newtons": 0, "elapsed_seconds": 0}
    for pair in range(pairs):
        sequence = [0, 1]
        rng.shuffle(sequence)
        for source_index in sequence:
            source = sources[source_index]
            if phase_jitter or feed_variation:
                source = source_at(
                    phases[source_index]
                    + source_rng.uniform(-phase_jitter, phase_jitter),
                    optical_feed_watts
                    * (1+source_rng.uniform(-feed_variation, feed_variation)))
            force = orientation*source["outgoing_radiation_recoil_component_newtons_xyz"][0]
            if not signal_enabled:
                force = 0
            force += (1 if source_index == 0 else -1)*artefact
            observations = observe(balance, [force]*samples_per_trial,
                                   [source["total_nonradiated_power_watts"]]*samples_per_trial,
                                   step_seconds, rng.randrange(2**32),
                                   initial_force_newtons=continuation["mechanical_newtons"],
                                   initial_thermal_newtons=continuation["thermal_newtons"],
                                   start_seconds=continuation["elapsed_seconds"])
            continuation = observations["continuation_state"]
            trials.append({"trial_id": f"T{len(trials)+1:03d}", "pair": pair,
                           "label": labels[source_index],
                           "readings_newtons": observations["readings_newtons"]})
            order.append(labels[source_index])
            source_trials.append({"trial_id": trials[-1]["trial_id"],
                                  "source": source,
                                  "start_seconds": continuation["elapsed_seconds"]
                                  -samples_per_trial*step_seconds,
                                  "orientation": orientation})
    public = {"status": "synthetic_blinded_acquisition_not_measurement",
              "sample_step_seconds": step_seconds, "trials": trials,
              "initial_state": "cold_zero_then_continuous_carryover"}
    truth = {"status": "simulation_truth_for_disclosure_only",
             "phase_key_radians": dict(zip(labels, phases)),
             "signal_enabled": signal_enabled, "null": null,
             "phase_correlated_force_newtons": artefact,
             "sources": sources, "acquisition_order": order,
             "source_geometry": {
                 "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}}
    if disclose_trial_sources or phase_jitter or feed_variation or orientation != 1:
        truth["source_trials"] = source_trials
        truth["injected_source_bounds"] = {
            "phase_jitter_bound_radians": phase_jitter,
            "feed_variation_bound_fraction": feed_variation,
            "orientation": orientation,
            "temporal_model": "trial_constant_jitter_not_within_trial_spectrum"}
    return public, truth


def analyse(observations: dict, *, tail_samples: int,
            differential_error_bound_newtons: float) -> dict:
    """Bound a labelled paired contrast without access to the hidden phase key.

    The supplied error bound must cover settling, calibration and every
    nuisance as well as readout noise. Repeated pairs do not shrink it.
    A resolved contrast alone cannot identify radiation as its cause.
    """
    error = bounded(differential_error_bound_newtons, 0, 1e-2, "difference error bound")
    if type(tail_samples) is not int or not 1 <= tail_samples <= 128:
        raise ValueError("tail samples must be an integer from 1 to 128")
    if type(observations) is not dict or set(observations) != {
            "status", "sample_step_seconds", "trials", "initial_state"}:
        raise ValueError("unsupported acquisition envelope or hidden fields")
    if observations["status"] != "synthetic_blinded_acquisition_not_measurement":
        raise ValueError("unsupported acquisition status")
    if observations["initial_state"] != "cold_zero_then_continuous_carryover":
        raise ValueError("unsupported initial state")
    bounded(observations["sample_step_seconds"], 0.001, 10, "sample step")
    trials = observations["trials"]
    if type(trials) is not list or not 4 <= len(trials) <= 32 or len(trials)%2:
        raise ValueError("expected 2 to 16 complete pairs")
    pairs = {}
    identifiers = set()
    sample_count = None
    for trial in trials:
        if type(trial) is not dict or set(trial) != {"trial_id", "pair", "label", "readings_newtons"}:
            raise ValueError("unsupported trial fields")
        identifier, pair, label = trial["trial_id"], trial["pair"], trial["label"]
        if (type(identifier) is not str or len(identifier) != 4
                or identifier[0] != "T" or not identifier[1:].isascii()
                or not identifier[1:].isdigit() or identifier in identifiers):
            raise ValueError("invalid or duplicate trial identifier")
        identifiers.add(identifier)
        if type(pair) is not int or not 0 <= pair < len(trials)//2 or label not in ("A", "B"):
            raise ValueError("invalid pair or label")
        readings = trial["readings_newtons"]
        if type(readings) is not list or not max(10, tail_samples) <= len(readings) <= 128:
            raise ValueError("missing or oversized readings")
        if sample_count is None:
            sample_count = len(readings)
        if len(readings) != sample_count:
            raise ValueError("unequal trial sample counts")
        for value in readings:
            bounded(value, -0.01, 0.01, "synthetic reading")
        group = pairs.setdefault(pair, {})
        if label in group:
            raise ValueError("duplicate pair label")
        group[label] = math.fsum(readings[-tail_samples:])/tail_samples
    if len(pairs) != len(trials)//2 or any(set(group) != {"A", "B"} for group in pairs.values()):
        raise ValueError("incomplete phase pair")
    contrasts = [pairs[index]["B"]-pairs[index]["A"] for index in range(len(pairs))]
    contrast = math.fsum(contrasts)/len(contrasts)
    guard = 64*math.ulp(max(abs(contrast), error))
    low, high = contrast-error-guard, contrast+error+guard
    return {"status": "synthetic_contrast_analysis_not_causal_evidence",
            "label_b_minus_a_newtons": contrast,
            "contrast_interval_newtons": [low, high],
            "pair_contrasts_newtons": contrasts,
            "supplied_differential_error_bound_newtons": error,
            "screen": "resolved_label_contrast" if low > 0 or high < 0 else "unresolved",
            "warning": "A correlated artefact can also resolve; disclose truth and inspect controls before interpretation."}
