"""Finite detector acquisition at actual passive-source power and trial age.

Synthetic readings only. Source parameters belong to acquisition, never to
the blind detector analyser. Calibration drift is a supplied bound, not a
measured drift law. No force-balance or causal verdict is assigned here.
"""

from detector_qualification import acquire, analyse
from detector_stability import aged_record, additive_force_bound
from recoil_budget import bounded


def acquire_trial(*, phase_radians, escaping_power_watts, end_seconds,
                  gain_drift_per_second=0, power_drift_watts_per_second=0,
                  additive_error_watts=0, grid=(8, 32), cone_degrees=2,
                  pointing_bound_degrees=0.01, gain_bound=0.0001,
                  total_power_bound_watts=0.0001, wavelength_m=1.55e-6,
                  aperture_radius_m=31e-6, separation_m=31e-6):
    """Return a public finite detector record and separate injection disclosure.

    The fixed wavefront geometry matches virtual_acquisition. Calibration
    starts at campaign time zero; trial end gives the conservative age for
    every reading within that trial. Absolute dark error is not power-scaled.
    The detector geometry and calibration bounds are declared inputs, not a
    measured instrument specification.
    """
    power = bounded(escaping_power_watts, 0.001, 100, "escaping trial power")
    age = bounded(end_seconds, 0, 3600, "trial end seconds")
    # Reject all uncertainty inputs before performing optical integration.
    bounded(gain_drift_per_second, 0, 0.001, "gain drift rate")
    bounded(power_drift_watts_per_second, 0, 0.001, "power drift rate")
    bounded(additive_error_watts, 0, 0.01, "aggregate additive error")
    gain = bounded(gain_bound, 0, 0.2, "per-pixel gain bound")
    power_bound = bounded(total_power_bound_watts, 0, 0.5,
                          "total power bound")
    if gain+age*gain_drift_per_second > 0.2:
        raise ValueError("aged gain bound exceeds detector limit")
    if power*power_bound+age*power_drift_watts_per_second > power/2:
        raise ValueError("aged total power bound exceeds detector limit")
    record, truth = acquire(phase_radians=phase_radians, grid=grid,
                            cone_degrees=cone_degrees,
                            pointing_bound_degrees=pointing_bound_degrees,
                            gain_bound=gain, actual_gain_amplitude=0,
                            total_power_bound_watts=power_bound,
                            wavelength_m=wavelength_m, aperture_radius_m=aperture_radius_m,
                            separation_m=separation_m)
    record = {**record, "total_power_reading_watts": power,
              "total_power_bound_watts": power*record["total_power_bound_watts"],
              "readings": [{**r, "power_reading_watts": power*r["power_reading_watts"]}
                           for r in record["readings"]]}
    record = aged_record(record, age, gain_drift_per_second,
                         power_drift_watts_per_second)
    # Keep the additive error outside the strict pixel-record schema.
    public = {"detector": record, "aggregate_additive_error_watts": additive_error_watts}
    return public, {**truth, "escaping_power_watts": power,
                    "calibration_age_seconds": age}


def analyse_trial(public):
    """Bound source-axis recoil using public readings only, not injection truth."""
    if type(public) is not dict or set(public) != {
            "detector", "aggregate_additive_error_watts"}:
        raise ValueError("expected public trial detector fields only")
    record = public["detector"]
    low, high = analyse(record).recoil_interval()
    extra = additive_force_bound(record, public["aggregate_additive_error_watts"])
    return [low-extra, high+extra]
