"""Find the primary and secondary rainbow radii for a spherical water drop."""
import json
import math
import platform
import sys

# Hale & Querry (1973), Table 1, liquid water at 25 °C.
COLORS = ((650, 1.331), (550, 1.333), (400, 1.339))
STEPS = 9000


def radius(i, n, reflections):
    r = math.asin(math.sin(i) / n)
    turn = reflections * math.pi + 2 * (i - (reflections + 1) * r)
    return math.degrees(math.acos(max(-1, min(1, -math.cos(turn)))))


def energy_fraction(i, n, reflections):
    r = math.asin(math.sin(i) / n)
    ci, cr = math.cos(i), math.cos(r)
    rs = ((ci - n * cr) / (ci + n * cr)) ** 2
    rp = ((n * ci - cr) / (n * ci + cr)) ** 2
    return sum((1 - reflectance) ** 2 * reflectance ** reflections
               for reflectance in (rs, rp)) / 2


def trace(wavelength, n, reflections):
    stationary = math.acos(math.sqrt((n * n - 1) / (reflections * (reflections + 2))))
    expected = radius(stationary, n, reflections)
    choose = max if reflections == 1 else min
    sampled = choose((radius(math.radians(i / 100), n, reflections), i / 100)
                     for i in range(STEPS + 1))
    assert abs(sampled[0] - expected) < 0.00001
    assert abs(sampled[1] - math.degrees(stationary)) <= 0.01
    return {
        "wavelength_nm": wavelength, "refractive_index": n,
        "internal_reflections": reflections,
        "incident_angle_deg": round(math.degrees(stationary), 6),
        "angular_radius_deg": round(expected, 6),
        "sampled_radius_deg": round(sampled[0], 6),
        "sampled_incident_angle_deg": sampled[1],
        "single_ray_energy_percent": round(100 * energy_fraction(stationary, n, reflections), 6),
    }


def run():
    rows = [trace(wavelength, n, order) for order in (1, 2) for wavelength, n in COLORS]
    primary = [row["angular_radius_deg"] for row in rows[:3]]
    secondary = [row["angular_radius_deg"] for row in rows[3:]]
    assert primary[0] > primary[1] > primary[2]
    assert secondary[0] < secondary[1] < secondary[2]
    gap = [max(primary), min(secondary)]
    assert gap[0] < 46 < gap[1]
    assert rows[1]["single_ray_energy_percent"] > rows[4]["single_ray_energy_percent"] > 0
    assert energy_fraction(0, 1.333, 2) < energy_fraction(0, 1.333, 1)
    assert abs(energy_fraction(math.pi / 2, 1.333, 1)) < 1e-12
    for _, n in COLORS:
        assert radius(0, n, 1) == 0
        assert radius(0, n, 2) == 180
        for angle in range(STEPS + 1):
            i = math.radians(angle / 100)
            assert radius(i, n, 1) <= gap[0] + 0.000001
            assert radius(i, n, 2) >= gap[1] - 0.000001
    elevations = [0, 20, 45, 55]
    red_primary = [round(primary[0] - height, 6) for height in elevations]
    red_secondary = [round(secondary[0] - height, 6) for height in elevations]
    violet_secondary = [round(secondary[2] - height, 6) for height in elevations]
    assert red_primary[2] < 0 < red_secondary[2]
    assert violet_secondary[3] < 0
    return {
        "environment": {"os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
                        "machine": platform.machine(), "python": sys.version.split()[0]},
        "incident_grid_deg": [0, 90, 0.01],
        "rows": rows,
        "gap_bounds_deg_for_these_wavelengths": gap,
        "sun_altitudes_deg": elevations,
        "red_primary_top_altitude_deg": red_primary,
        "red_secondary_top_altitude_deg": red_secondary,
        "violet_secondary_top_altitude_deg": violet_secondary,
        "central_incidence_radius_deg_by_order": [0, 180],
    }


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
