"""Reduced passive two-port optical feed for the prescribed wavefront family.

This candidate contraction model closes a settled optical power account. It
does not identify a manufactured splitter, phase shifter or source impedance.
"""

import argparse
import json
import math

from optical_reference import predict as wavefront
from recoil_budget import LIGHT_SPEED_M_S, OnceFloat, bounded, numeric_option, parse_options


def predict(wavelength_m: float, aperture_radius_m: float, separation_m: float,
            phase_radians: float, optical_feed_power_watts: float,
            laser_conversion_efficiency: float, control_power_watts: float) -> dict[str, object]:
    phase = bounded(phase_radians, -math.pi, math.pi, "phase")
    feed = bounded(optical_feed_power_watts, 1e-12, 1e9, "optical feed power")
    efficiency = bounded(laser_conversion_efficiency, 1e-6, 1, "laser conversion efficiency")
    control = bounded(control_power_watts, 0, 1e9, "phase-control electrical power")
    electrical = feed / efficiency + control
    if electrical > 1e9:
        raise ValueError("conditional complete electrical input exceeds 1 GW limit")
    # Mode overlap is obtained from the same transverse field, not from a
    # scalar/RF substitution. Equal sources have equal diagonal Gram terms.
    in_phase = wavefront(wavelength_m, aperture_radius_m, separation_m, 0, 1, 1)
    quarter = wavefront(wavelength_m, aperture_radius_m, separation_m, math.pi/2, 1, 1)
    overlap = (in_phase["unscaled_pattern_integral_steradians"]
               / quarter["unscaled_pattern_integral_steradians"] - 1)
    if abs(overlap) > 1 + 1e-12:
        raise ArithmeticError("radiator mode Gram matrix is not positive semidefinite")
    overlap = max(-1.0, min(1.0, overlap))
    if separation_m == 0:
        # Identical modes have exactly unit overlap. Preserve the analytic dark
        # port instead of turning quadrature roundoff into invented radiation.
        overlap = 1.0
    # G = [[1,C],[C,1]]. Dividing by its maximum eigenvalue makes
    # T^dagger T = G/(1+|C|) a contraction. The complementary port is
    # explicitly absorbed inside the mechanical boundary, not discarded.
    phase_factor = math.cos(phase/2) if overlap >= 0 else math.sin(phase/2)
    fraction = (1 - abs(overlap) + 2 * abs(overlap) * phase_factor**2) / (1 + abs(overlap))
    exact_dark = separation_m == 0 and abs(phase) == math.pi
    if exact_dark:
        fraction = 0.0
    radiated = feed * fraction
    auxiliary_absorbed = feed - radiated
    if exact_dark:
        vector = [0.0, 0.0, 0.0]
        state = "dark_radiator_all_feed_to_internal_absorber"
    elif fraction <= 1e-12:
        raise ValueError("near-dark port fraction is below the qualified normalisation floor")
    else:
        field = wavefront(wavelength_m, aperture_radius_m, separation_m, phase, 1, 1)
        vector = field["outgoing_direction_cosine_mean_xyz"]
        state = "radiating"
    upstream_loss = feed / efficiency - feed
    nonradiated = upstream_loss + auxiliary_absorbed + control
    residual = electrical - radiated - nonradiated
    if abs(residual) > 1e-12 * max(1, electrical):
        raise ArithmeticError("settled candidate power account did not close")
    return {
        "status": "reduced_passive_optical_feed_reference_not_hardware",
        "model": "two_equal_mode_contraction_internal_complementary_absorber_v1",
        "phase_radians": phase,
        "mode_real_overlap": overlap,
        "radiated_fraction_of_optical_feed": fraction,
        "optical_feed_power_watts": feed,
        "escaping_radiated_power_watts": radiated,
        "internal_complementary_absorber_watts": auxiliary_absorbed,
        "laser_conversion_loss_watts": upstream_loss,
        "phase_control_power_watts": control,
        "total_electrical_input_watts": electrical,
        "total_nonradiated_power_watts": nonradiated,
        "thermal_recoil_bound_if_all_nonradiated_power_escapes_as_radiation_newtons":
        nonradiated / LIGHT_SPEED_M_S,
        "settled_power_residual_watts": residual,
        "outgoing_radiation_recoil_component_newtons_xyz":
        [-radiated * value / LIGHT_SPEED_M_S for value in vector],
        "state": state,
        "warning": "A specified passive port model, not an implemented feed; complete recoil still requires thermal radiation, incoming momentum and mechanical interaction bounds.",
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
    for field in ("wavelength_m", "aperture_radius_m", "separation_m", "phase_radians",
                  "optical_feed_power_watts", "laser_conversion_efficiency", "control_power_watts"):
        parser.add_argument("--" + field.replace("_", "-"), type=numeric_option, action=OnceFloat, required=True)
    try:
        result = predict(**vars(parse_options(parser)))
    except (ValueError, ArithmeticError) as error:
        parser.error(str(error))
    print(json.dumps(result, sort_keys=True, separators=(",", ":"), allow_nan=False))


if __name__ == "__main__":
    main()
