"""Prescribed transverse Maxwell far-field reference for two optical apertures.

The forward-hemisphere angular amplitude has a Gaussian envelope, a cosine
obliquity factor and a transverse y-polarisation projection. This is a candidate
wavefront, not a hardware solution, a self-consistent driver or PF-002 evidence.
"""

from __future__ import annotations

import argparse
import json
import math

from recoil_budget import LIGHT_SPEED_M_S, OnceFloat, bounded, numeric_option, parse_options


def _gauss_legendre(order: int) -> list[tuple[float, float]]:
    """Fixed, bounded Newton construction; orders are internal, not user inputs."""
    if order not in (64, 128):
        raise ValueError("unsupported internal radial order")
    nodes = []
    for index in range(1, order + 1):
        root = math.cos(math.pi * (index - 0.25) / (order + 0.5))
        for _ in range(16):
            previous, polynomial = 1.0, root
            for degree in range(2, order + 1):
                previous, polynomial = polynomial, ((2 * degree - 1) * root * polynomial
                                                     - (degree - 1) * previous) / degree
            derivative = order * (root * polynomial - previous) / (root * root - 1)
            delta = polynomial / derivative
            root -= delta
            if abs(delta) < 1e-15:
                break
        else:
            raise ArithmeticError("radial quadrature construction did not converge")
        # Re-evaluate derivative at the final root before forming the weight.
        previous, polynomial = 1.0, root
        for degree in range(2, order + 1):
            previous, polynomial = polynomial, ((2 * degree - 1) * root * polynomial
                                                 - (degree - 1) * previous) / degree
        derivative = order * (root * polynomial - previous) / (root * root - 1)
        weight = 2 / ((1 - root * root) * derivative * derivative)
        nodes.append((root, weight))
    return nodes


def _moments(kw: float, separation_over_width: float, phase: float,
             radial_order: int, azimuth_count: int) -> tuple[float, float, float, float]:
    # t = kw*sin(theta). dOmega = t/(kw^2*mu) dt dphi. The squared
    # obliquity factor mu^2 cancels the hemisphere rim singularity. kw^-2
    # cancels in normalised moments, so retain scaled integrals here.
    if azimuth_count not in (128, 256):
        raise ValueError("unsupported internal azimuth count")
    angle_step = 2 * math.pi / azimuth_count
    angles = [(math.cos(index * angle_step), math.sin(index * angle_step))
              for index in range(azimuth_count)]
    energy = x_moment = y_moment = z_moment = 0.0
    for node, weight in _gauss_legendre(radial_order):
        t = 6 * (node + 1)  # integrate 0 <= t <= 12
        radius = t / kw
        mu = math.sqrt(1 - radius * radius)
        envelope_weight = math.exp(-t * t / 2) * mu * t * 6 * weight * angle_step
        for cosine, sine in angles:
            nx, ny = radius * cosine, radius * sine
            array_factor = 4 * math.cos((phase + separation_over_width * t * cosine) / 2) ** 2
            power = envelope_weight * (1 - ny * ny) * array_factor
            energy += power
            x_moment += power * nx
            y_moment += power * ny
            z_moment += power * mu
    if not math.isfinite(energy) or energy <= 1e-20:
        raise ValueError("near-dark prescribed source cannot be normalised to positive radiated power")
    return energy, x_moment / energy, y_moment / energy, z_moment / energy


def predict(wavelength_m: float, aperture_radius_m: float, separation_m: float,
            phase_radians: float, radiated_power_watts: float,
            total_efficiency: float) -> dict[str, object]:
    """Compute conditional outgoing momentum at explicitly fixed radiated power.

    The amplitude radius w describes exp(-r^2/w^2) at an idealised aperture.
    Driver losses use a supplied whole-system efficiency, never a catalogue
    inference. Source coupling and incoming momentum are not solved here.
    """
    wavelength = bounded(wavelength_m, 1e-7, 0.1, "wavelength")
    radius = bounded(aperture_radius_m, 2 * wavelength, 1e4 * wavelength, "aperture radius")
    separation = bounded(separation_m, 0, 8 * radius, "separation")
    phase = bounded(phase_radians, -math.pi, math.pi, "phase")
    power = bounded(radiated_power_watts, 1e-12, 1e9, "radiated power")
    efficiency = bounded(total_efficiency, 1e-6, 1, "total efficiency")
    if power / efficiency > 1e9:
        raise ValueError("conditional electrical input exceeds 1 GW input limit")
    kw = 2 * math.pi * radius / wavelength
    coarse = _moments(kw, separation / radius, phase, 64, 128)
    fine = _moments(kw, separation / radius, phase, 128, 256)
    integration_change = max(abs(a - b) for a, b in zip(coarse[1:], fine[1:]))
    power_change = abs(coarse[0] - fine[0]) / fine[0]
    if integration_change > 1e-7 or power_change > 1e-7:
        raise ArithmeticError("angular quadrature failed its fixed refinement check")
    vector = list(fine[1:])
    if sum(value * value for value in vector) > 1 + 1e-12:
        raise ArithmeticError("outgoing momentum violates the photon bound")
    # Outside t=12, polarisation and obliquity are <=1 and the array factor
    # <=4. Integrating t*exp(-t^2/2) gives a conservative omitted-power bound.
    tail_fraction_bound = 8 * math.pi * math.exp(-72) / fine[0]
    recoil = [-power * value / LIGHT_SPEED_M_S for value in vector]
    return {
        "status": "prescribed_optical_wavefront_reference_not_measurement",
        "model": "forward_gaussian_cosine_obliquity_transverse_y_two_apertures_v1",
        "wavelength_m": wavelength,
        "aperture_amplitude_radius_m": radius,
        "separation_m": separation,
        "phase_radians": phase,
        "radiated_power_watts": power,
        "supplied_total_efficiency": efficiency,
        "conditional_electrical_input_watts": power / efficiency,
        "conditional_nonradiated_power_watts": power / efficiency - power,
        "outgoing_direction_cosine_mean_xyz": vector,
        "outgoing_radiation_recoil_component_newtons_xyz": recoil,
        "unscaled_pattern_integral_steradians": fine[0] / (kw * kw),
        "quadrature_refinement_max_moment_change": integration_change,
        "quadrature_refinement_relative_power_change": power_change,
        "omitted_angular_power_fraction_bound": tail_fraction_bound,
        "limits": {"radial_nodes": 128, "azimuth_nodes": 256,
                   "total_pattern_evaluations": 40960, "retries": 0},
        "warning": "Fixed radiated power, prescribed wavefront and supplied efficiency only; feed, mutual coupling, phase noise and boundary forces require separate qualification.",
    }


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


if __name__ == "__main__":
    main()
