"""Synthetic finite-pixel optical detector qualification, not hardware evidence.

The source is the specified 1550 nm, 31 micrometre two-aperture reference.
Pixel power is integrated, not point-sampled. Analysis sees only readings and
supplied calibration bounds; unseen momentum remains arbitrary.
"""

import json
import math
import sys

from optical_reference import predict
from recoil_budget import PhaseBudget, bounded, screen

WAVELENGTH = 1.55e-6
RADIUS = SEPARATION = 31e-6
NUMERICAL_ALLOWANCE = 1e-6
GRIDS = ((8, 32), (16, 64), (32, 64))
RULES = {
    2: ((-1/math.sqrt(3), 1), (1/math.sqrt(3), 1)),
    4: ((-0.8611363115940526, 0.3478548451374538),
        (-0.3399810435848563, 0.6521451548625461),
        (0.3399810435848563, 0.6521451548625461),
        (0.8611363115940526, 0.3478548451374538)),
    8: ((-0.9602898564975363, 0.1012285362903763),
        (-0.7966664774136267, 0.2223810344533745),
        (-0.5255324099163290, 0.3137066458778873),
        (-0.1834346424956498, 0.3626837833783620),
        (0.1834346424956498, 0.3626837833783620),
        (0.5255324099163290, 0.3137066458778873),
        (0.7966664774136267, 0.2223810344533745),
        (0.9602898564975363, 0.1012285362903763)),
}


def _direction(theta, phi, tilt):
    s, c = math.sin(theta), math.cos(theta)
    return (math.cos(tilt)*s*math.cos(phi)+math.sin(tilt)*c,
            s*math.sin(phi), math.cos(tilt)*c-math.sin(tilt)*s*math.cos(phi))


def _pixel(theta_low, theta_high, phi_low, phi_high, tilt, phase, order,
           wavelength=WAVELENGTH, radius=RADIUS, separation=SEPARATION):
    total = 0.0
    kw = 2*math.pi*radius/wavelength
    kd = 2*math.pi*separation/wavelength
    for radial, rw in RULES[order]:
        theta = (theta_low+theta_high)/2 + radial*(theta_high-theta_low)/2
        for azimuth, aw in RULES[order]:
            phi = (phi_low+phi_high)/2 + azimuth*(phi_high-phi_low)/2
            nx, ny, nz = _direction(theta, phi, tilt)
            intensity = math.exp(-kw*kw*(nx*nx+ny*ny)/2) * nz*nz * (1-ny*ny)
            intensity *= 4*math.cos((phase+kd*nx)/2)**2
            total += intensity*math.sin(theta)*rw*aw
    return total*(theta_high-theta_low)*(phi_high-phi_low)/4


def _geometry(cone_degrees, tilt_degrees, pointing_bound_degrees, grid, missing_quarter):
    cone = math.radians(bounded(cone_degrees, 0.5, 4, "cone half angle"))
    tilt = math.radians(bounded(tilt_degrees, -2, 2, "nominal x-axis tilt"))
    pointing = math.radians(bounded(pointing_bound_degrees, 0, 0.5, "pointing bound"))
    if type(grid) is not tuple or grid not in GRIDS or any(type(n) is not int for n in grid):
        raise ValueError("unsupported finite pixel grid")
    if type(missing_quarter) is not bool:
        raise ValueError("missing-quarter mask must be boolean")
    rings, sectors = grid
    cells = []
    for ring in range(rings):
        tl, th = cone*ring/rings, cone*(ring+1)/rings
        for sector in range(sectors):
            if missing_quarter and sector < sectors//4:
                continue
            pl, ph = 2*math.pi*sector/sectors, 2*math.pi*(sector+1)/sectors
            centre = _direction((tl+th)/2, (pl+ph)/2, tilt)[0]
            # Angular path length bounds chord distance and each component:
            # radial half-width + sin(theta_max)*azimuth half-width + tilt error.
            extent = (th-tl)/2 + math.sin(th)*(ph-pl)/2 + pointing
            cells.append((ring*sectors+sector, tl, th, pl, ph,
                          max(-1, centre-extent), min(1, centre+extent)))
    return cone, tilt, pointing, cells


def acquire(cone_degrees=2, tilt_degrees=0, pointing_bound_degrees=0.01,
            actual_pointing_error_degrees=0, grid=(32, 64), missing_quarter=False,
            gain_bound=0.01, actual_gain_amplitude=0.005, phase_radians=math.pi/2,
            total_power_bound_watts=0.01, wavelength_m=WAVELENGTH,
            aperture_radius_m=RADIUS, separation_m=SEPARATION):
    cone, tilt, pointing, cells = _geometry(cone_degrees, tilt_degrees,
                                            pointing_bound_degrees, grid, missing_quarter)
    gain = bounded(gain_bound, 0, 0.2, "per-pixel gain bound")
    amplitude = bounded(actual_gain_amplitude, -gain, gain, "injected gain amplitude")
    error = math.radians(bounded(actual_pointing_error_degrees,
                                -pointing_bound_degrees, pointing_bound_degrees,
                                "injected pointing error"))
    phase = bounded(phase_radians, -math.pi, math.pi, "source phase")
    power_bound = bounded(total_power_bound_watts, 0, 0.5, "total power bound")
    reference = predict(wavelength_m, aperture_radius_m, separation_m, phase, 1, 1)
    norm = reference["unscaled_pattern_integral_steradians"]
    readings, difference = [], 0.0
    for ident, tl, th, pl, ph, _, _ in cells:
        coarse = _pixel(tl, th, pl, ph, tilt+error, phase, 4,
                        wavelength_m, aperture_radius_m, separation_m)/norm
        fine = _pixel(tl, th, pl, ph, tilt+error, phase, 8,
                      wavelength_m, aperture_radius_m, separation_m)/norm
        difference += abs(coarse-fine)
        # Deliberately nonuniform calibration error, not cancelling by phase.
        reading = fine*(1+amplitude*math.sin(ident+0.5))
        readings.append({"pixel": ident, "power_reading_watts": reading})
    if difference > NUMERICAL_ALLOWANCE:
        raise ArithmeticError("pixel power integration failed fixed refinement")
    public = {"model": "tilted_cone_integrated_pixels_bounded_gain_v1",
              "cone_degrees": cone_degrees, "tilt_degrees": tilt_degrees,
              "pointing_bound_degrees": pointing_bound_degrees,
              "grid": list(grid), "missing_quarter": missing_quarter,
              "gain_bound": gain, "total_power_reading_watts": 1.0,
              "total_power_bound_watts": power_bound, "readings": readings}
    truth = {"actual_pointing_error_degrees": actual_pointing_error_degrees,
             "source_geometry": {"wavelength_m": wavelength_m,
                                 "aperture_radius_m": aperture_radius_m,
                                 "separation_m": separation_m},
             "actual_gain_amplitude": amplitude, "phase_radians": phase,
             "true_full_pattern_mean_x": reference["outgoing_direction_cosine_mean_xyz"][0],
             "quadrature_sum_absolute_power_change": difference,
             "omitted_tail_fraction_bound": reference["omitted_angular_power_fraction_bound"]}
    return public, truth


def analyse(record):
    fields = {"model", "cone_degrees", "tilt_degrees", "pointing_bound_degrees",
              "grid", "missing_quarter", "gain_bound", "total_power_reading_watts",
              "total_power_bound_watts", "readings"}
    if type(record) is not dict or set(record) != fields:
        raise ValueError("expected public detector record only")
    if record["model"] != "tilted_cone_integrated_pixels_bounded_gain_v1":
        raise ValueError("unsupported detector model")
    if type(record["grid"]) is not list or len(record["grid"]) != 2:
        raise ValueError("expected declared pixel grid")
    _, _, _, cells = _geometry(record["cone_degrees"], record["tilt_degrees"],
                               record["pointing_bound_degrees"], tuple(record["grid"]),
                               record["missing_quarter"])
    gain = bounded(record["gain_bound"], 0, 0.2, "per-pixel gain bound")
    power = bounded(record["total_power_reading_watts"], 0.001, 100, "total power")
    uncertainty = bounded(record["total_power_bound_watts"], 0, power/2, "total power bound")
    readings = record["readings"]
    if type(readings) is not list or len(readings) != len(cells):
        raise ValueError("missing or unexpected detector readings")
    observed_low = observed_high = numerator_low = numerator_high = 0.0
    for reading, (ident, _, _, _, _, direction_low, direction_high) in zip(readings, cells):
        if (type(reading) is not dict or set(reading) != {"pixel", "power_reading_watts"}
                or type(reading["pixel"]) is not int or reading["pixel"] != ident):
            raise ValueError("duplicate, reordered or unexpected pixel")
        value = bounded(reading["power_reading_watts"], 0, 100, "pixel power")
        low, high = value/(1+gain), value/(1-gain)
        observed_low += low
        observed_high += high
        products = [w*n for w in (low, high) for n in (direction_low, direction_high)]
        numerator_low += min(products)
        numerator_high += max(products)
    # Fixed supplied design allowance covers empirical integration refinement
    # and the negligible Gaussian tail for this fixed, non-dark source family.
    extra = (power+uncertainty)*NUMERICAL_ALLOWANCE
    observed_low = max(0, observed_low-extra)
    observed_high += extra
    if observed_low <= 1e-20 or observed_low > power+uncertainty:
        raise ValueError("unusable or inconsistent collected power")
    fraction_low = observed_low/(power+uncertainty)
    fraction_high = min(1, observed_high/(power-uncertainty))
    moments = [n/w for n in (numerator_low-extra, numerator_high+extra)
               for w in (observed_low, observed_high)]
    moment_low, moment_high = max(-1, min(moments)), min(1, max(moments))
    budget = PhaseBudget(power, uncertainty, (fraction_low+fraction_high)/2,
                         (fraction_high-fraction_low)/2,
                         (moment_low+moment_high)/2, (moment_high-moment_low)/2)
    budget.recoil_interval()
    return budget


def campaign():
    configurations = [
        ("centred", 2, 0, (32, 64), False, 0.01),
        ("offset-half-degree", 2, 0.5, (32, 64), False, 0.01),
        ("offset-one-degree", 2, 1, (32, 64), False, 0.01),
        ("offset-two-degrees", 2, 2, (32, 64), False, 0.01),
        ("negative-offset", 2, -0.5, (32, 64), False, 0.01),
        ("wide-offset", 4, 2, (32, 64), False, 0.01),
        ("coarse-pixels", 2, 0, (8, 32), False, 0.01),
        ("middle-pixels", 2, 0, (16, 64), False, 0.01),
        ("large-gain-bound", 2, 0, (32, 64), False, 0.1),
        ("missing-quarter", 4, 0, (32, 64), True, 0.01),
    ]
    rows = []
    configurations = [row+(0.01, 0.01) for row in configurations]
    configurations += [
        ("tight-calibration", 2, 0, (32, 64), False, 0.0001, 0.0001, 0.01),
        ("tight-offset", 2, 0.5, (32, 64), False, 0.0001, 0.0001, 0.01),
        ("tight-wide-offset", 4, 2, (32, 64), False, 0.0001, 0.0001, 0.01),
        ("tight-coarse", 2, 0, (8, 32), False, 0.0001, 0.0001, 0.01),
        ("tight-poor-pointing", 2, 0, (32, 64), False, 0.0001, 0.0001, 0.5),
    ]
    for name, cone, tilt, grid, missing, gain, power_bound, pointing in configurations:
        records = [acquire(cone, tilt, pointing_bound_degrees=pointing,
                           grid=grid, missing_quarter=missing,
                           gain_bound=gain, actual_gain_amplitude=gain/2,
                           total_power_bound_watts=power_bound, phase_radians=phase)[0]
                   for phase in (math.pi/2, -math.pi/2)]
        a, b = [analyse(record) for record in records]
        budget = screen(a, b, 1e-13, 1e-13)
        rows.append({"case": name, "cone_degrees": cone, "tilt_degrees": tilt,
                     "grid": list(grid), "missing_quarter": missing, "gain_bound": gain,
                     "pointing_bound_degrees": pointing,
                     "total_power_bound_watts": power_bound,
                     "coverage_intervals": [[v.observed_fraction-v.observed_fraction_bound,
                                             v.observed_fraction+v.observed_fraction_bound]
                                            for v in (a, b)],
                     "budget": budget,
                     "differential_noise_must_be_strictly_below_newtons": max(
                         0, budget["minimum_predicted_difference_newtons"]
                         -1e-13-budget["arithmetic_guard_newtons"])})
    return {"status": "detector_qualification_design_not_physical_evidence",
            "source": {"wavelength_m": WAVELENGTH, "radius_m": RADIUS,
                       "separation_m": SEPARATION, "radiated_power_per_phase_watts": 1},
            "numerical_design_allowance": NUMERICAL_ALLOWANCE,
            "limits": {"cases": 15, "phase_acquisitions": 30,
                       "maximum_pixels_per_acquisition": 2048,
                       "maximum_pattern_evaluations_per_acquisition": 204800,
                       "output_bytes": 65536, "retries": 0}, "rows": rows,
            "warning": "Synthetic integrated pixel readings and supplied bounds only. No calibrated instrument, manufactured feed, physical PF-002 result or new propulsion claim. Unknown momentum and errors do not cancel by assumption."}


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


if __name__ == "__main__":
    main()
