"""Bounded calibration-age and additive detector-error design study.

No physical calibration, probabilistic averaging or phase cancellation inferred.
"""

import json
import math
import sys

from detector_qualification import acquire, analyse
from recoil_budget import LIGHT_SPEED_M_S, bounded, screen


def aged_record(record, age_seconds, gain_drift_per_second,
                power_drift_watts_per_second):
    # Validate the original public boundary, including hidden/missing records.
    analyse(record)
    age = bounded(age_seconds, 0, 3600, "calibration age seconds")
    gain_rate = bounded(gain_drift_per_second, 0, 0.001, "gain drift rate")
    power_rate = bounded(power_drift_watts_per_second, 0, 0.001, "power drift rate")
    updated = dict(record)
    updated["gain_bound"] = bounded(record["gain_bound"] + age*gain_rate,
                                    0, 0.2, "aged gain bound")
    updated["total_power_bound_watts"] = bounded(
        record["total_power_bound_watts"] + age*power_rate,
        0, record["total_power_reading_watts"]/2, "aged total power bound")
    analyse(updated)
    return updated


def additive_force_bound(record, aggregate_error_watts):
    """Worst-case extra uncertainty in outgoing axial momentum per phase.

    E bounds the sum of absolute pixel power errors AFTER gain correction.
    Observed axial error is <= E*max(abs(nx)); residual missing-power error
    is <= E because its direction is unknown. No channel cancellation used.
    """
    analyse(record)
    error = bounded(aggregate_error_watts, 0, 0.01, "aggregate additive error")
    angle = math.radians(record["cone_degrees"] + abs(record["tilt_degrees"])
                         + record["pointing_bound_degrees"])
    return error*(1+math.sin(angle))/LIGHT_SPEED_M_S


def evaluate(records, ages_seconds, gain_drift_per_second=0,
             power_drift_watts_per_second=0, additive_errors_watts=(0, 0),
             force_noise_newtons=1e-13, nuisance_newtons=1e-13):
    for values in (records, ages_seconds, additive_errors_watts):
        if type(values) not in (tuple, list) or len(values) != 2:
            raise ValueError("exactly two phase entries required")
    nuisance = bounded(nuisance_newtons, 0, 1, "paired apparatus nuisance")
    noise = bounded(force_noise_newtons, 0, 1, "paired force noise")
    aged = [aged_record(r, age, gain_drift_per_second, power_drift_watts_per_second)
            for r, age in zip(records, ages_seconds)]
    additive = sum(additive_force_bound(r, e)
                   for r, e in zip(aged, additive_errors_watts))
    result = screen(*(analyse(r) for r in aged), noise, nuisance+additive)
    return {"budget": result, "paired_additive_force_bound_newtons": additive,
            "aged_gain_bounds": [r["gain_bound"] for r in aged],
            "aged_total_power_bounds_watts": [r["total_power_bound_watts"] for r in aged],
            "force_noise_must_be_strictly_below_newtons": max(
                0, result["minimum_predicted_difference_newtons"]
                -nuisance-additive-result["arithmetic_guard_newtons"])}


def campaign():
    records = [acquire(gain_bound=0.0001, actual_gain_amplitude=0,
                       total_power_bound_watts=0.0001, phase_radians=p)[0]
               for p in (math.pi/2, -math.pi/2)]
    cases = (
        ("fresh", (0, 0), 0, 0, (0, 0)),
        ("one-minute", (60, 61), 1e-6, 1e-6, (1e-5, 1e-5)),
        ("ten-minute", (600, 601), 1e-6, 1e-6, (1e-5, 1e-5)),
        ("stale-hour", (3599, 3600), 1e-6, 1e-6, (1e-5, 1e-5)),
        ("dark-readout-dominated", (0, 0), 0, 0, (0.005, 0.005)),
    )
    rows = [{"case": name, "calibration_ages_seconds": ages,
             "gain_drift_per_second": gain, "power_drift_watts_per_second": power,
             "aggregate_additive_errors_watts": errors,
             **evaluate(records, ages, gain, power, errors)}
            for name, ages, gain, power, errors in cases]
    rows.append({"case": "same-phase-null", **evaluate([records[0], records[0]], (0, 0))})
    return {"status": "synthetic_detector_stability_not_physical_evidence",
            "rows": rows, "limits": {"cases": 6, "source_acquisitions": 2,
                                      "output_bytes": 32768, "retries": 0},
            "warning": "Supplied drift and additive error bounds only; no measured stability, cancellation, averaging gain or hardware readiness."}


def main():
    if len(sys.argv) != 1:
        raise SystemExit("Fixed stability campaign accepts no arguments")
    output = json.dumps(campaign(), allow_nan=False, sort_keys=True)
    if len(output.encode()) > 32768:
        raise SystemExit("stability output exceeds 32 KiB")
    print(output)


if __name__ == "__main__":
    main()
