#!/usr/bin/env python3
"""Part two, page 03: the Moon, then Mars. The numbers behind Fig. 13 and its notes.

Every number on the page comes from this script (Python standard library only), or repeats an
earlier page's assumption, marked as such below. --write publishes the JSON and a copy of this
script alongside the page. The geometry is idealised: spherical bodies, circular orbits, a
cylindrical shadow and level ground around the site. Nothing here is measured.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

# The Moon, from NASA's Moon Fact Sheet (source 10).
R_MOON = 1737.4                 # km, volumetric mean radius
MU_MOON = 4900.0                # km^3 s^-2, GM = 0.00490 x 10^6
MOON_DISTANCE_KM = 384400.0     # semimajor axis of its orbit about Earth, 0.3844 x 10^6 km
MOON_OBLIQUITY_TO_ORBIT = 6.68  # deg
MOON_ORBIT_TO_ECLIPTIC = 5.145  # deg
# Cassini's laws: the Moon's equator, its orbit and the ecliptic share a line of nodes, with the
# orbit's pole between the other two. So the equator is tilted 6.68 - 5.145 = 1.54 degrees to the
# ecliptic, and the Sun is never more than that above or below a lunar pole's horizon.
SUN_TILT_MOON = MOON_OBLIQUITY_TO_ORBIT - MOON_ORBIT_TO_ECLIPTIC

# Mars, from NASA's Mars Fact Sheet (source 12).
R_MARS = 3389.5                 # km, volumetric mean radius
MU_MARS = 42828.0               # km^3 s^-2, GM = 0.042828 x 10^6
MARS_SIDEREAL_H = 24.6229       # sidereal rotation period
MARS_DAY_H = 24.6597            # length of day
MARS_IRRADIANCE = 586.2         # W m^-2
EARTH_IRRADIANCE = 1361.0       # W m^-2, as on page 13
MARS_DISTANCE_KM = [54.6e6, 401.4e6]   # minimum and maximum distance from Earth

C_KM_S = 299792.458             # speed of light, exact

ASSUMPTIONS = {
    'pack_wh_per_kg': [100, 200],         # page 7, inside NASA's pack range (source 1)
    'usable_share_night': 0.8,            # page 7, our assumption
    'lunar_night_hours': 354,             # source 4
    'wavelength_um': 1.0,                 # page 9
    'apertures_m': [0.5, 2.0],            # page 9
    'link_efficiency': 0.2,               # page 8: laser 0.5 x capture 0.8 x receiver 0.5
    'laser_input_kw': 5.0,                # page 12's satellite: 5 kW of laser input delivers 1 kW
    'min_elevation_deg': 20.0,            # our assumption: high enough to clear a crater's walls
    'polar_altitudes_km': [500, 1000, 1500, 3000],
    'design_altitude_km': 1000,           # the polar ring drawn in Fig. 12
    'mars_hover_offsets_deg': [30.0],     # two hovering satellites, 30 degrees either side of a site
    'dust_optical_depths': [1.0, 5.5, 10.8],   # 1 for scale; 2007 and 2018 storms (source 18)
}


def period_h(mu, r_km):
    return 2 * math.pi * math.sqrt(r_km ** 3 / mu) / 3600


def spot_m(distance_km, aperture_m, wavelength_um):
    """Diameter of the beam's central spot (to the first dark ring), as under Fig. 2."""
    return 2.44 * wavelength_um * 1e-6 * distance_km * 1e3 / aperture_m


def window_half_angle(radius, r, min_elevation):
    """Half the arc of an orbit (seen from the body's centre) over which a site sees the satellite
    above min_elevation, when the orbit passes straight over the site."""
    return math.acos(radius / r * math.cos(min_elevation)) - min_elevation


def slant_range(radius, r, elevation):
    return math.sqrt(r ** 2 - (radius * math.cos(elevation)) ** 2) - radius * math.sin(elevation)


def lowest_sunlit_clearance(r, half_angle, tilt):
    """A satellite in a polar orbit passing over the south pole, with the Sun `tilt` below the pole's
    horizon (its local winter, the worst case). Returns the smallest margin, in km, by which the
    satellite clears the edge of the Moon's shadow across its window, over every orientation of the
    orbit around the pole. Positive means the whole window is in sunlight."""
    sun = (-math.cos(tilt), 0.0, math.sin(tilt))     # towards the Sun; the pole is at (0, 0, -R)
    worst = math.inf
    for b in range(0, 361, 5):
        turn = math.radians(b)
        for step in range(-200, 201):
            theta = half_angle * step / 200
            p = (r * math.sin(theta) * math.cos(turn), r * math.sin(theta) * math.sin(turn), -r * math.cos(theta))
            along = sum(a * s for a, s in zip(p, sun))
            if along >= 0:
                continue                             # on the day side: lit
            off_axis = math.sqrt(max(0.0, r * r - along * along))
            worst = min(worst, off_axis - R_MOON)
    return worst


def polar_ring(altitude_km, a):
    """A ring in a polar orbit, serving a site at a lunar pole, such as a crater floor."""
    r = R_MOON + altitude_km
    e = math.radians(a['min_elevation_deg'])
    half = window_half_angle(R_MOON, r, e)
    period = period_h(MU_MOON, r)
    share = 2 * half / (2 * math.pi)
    need = lambda k: math.ceil(k * math.pi / half - 1e-9)
    far = slant_range(R_MOON, r, e)
    # The satellite's own night: with the orbit in the noon-midnight plane (the worst case), it is
    # in the Moon's shadow for 2 arcsin(R / r) of each orbit.
    shadow_share = 2 * math.asin(R_MOON / r) / (2 * math.pi)
    lit_share = 1 - shadow_share
    return {
        'altitude_km': altitude_km,
        'period_h': period,
        'window_min': share * period * 60,
        'window_share': share,
        'satellites_for_one': need(1),
        'satellites_for_two': need(2),
        'range_km': [altitude_km, far],
        'spot_at_farthest_m': {str(d): spot_m(far, d, a['wavelength_um']) for d in a['apertures_m']},
        'sunlit_clearance_km': lowest_sunlit_clearance(r, half, math.radians(SUN_TILT_MOON)),
        'own_shadow_share': shadow_share,
        # Banking the sunlight from the rest of the orbit and spending it over the pole multiplies a
        # satellite's beam by this much, if its laser, radiators and battery can take it.
        'store_and_spend_gain': lit_share / share,
        'stored_kwh_per_orbit': a['laser_input_kw'] * (lit_share - share) * period,
    }


def mars_hover(a):
    """Satellites that hover over Mars's equator (areostationary), placed either side of a site.
    At midnight the site faces away from the Sun; a hovering satellite is in Mars's shadow within
    arcsin(R / r) of the anti-Sun line (at equinox, the worst case), so two placed 30 degrees either
    side take turns through the night."""
    r = (MU_MARS * (MARS_SIDEREAL_H * 3600 / (2 * math.pi)) ** 2) ** (1 / 3)
    shadow_half = math.degrees(math.asin(R_MARS / r))
    horizon_half = math.degrees(math.acos(R_MARS / r))
    out = []
    for offset in a['mars_hover_offsets_deg']:
        d = math.radians(offset)
        distance = math.sqrt(R_MARS ** 2 + r ** 2 - 2 * R_MARS * r * math.cos(d))
        elevation = math.degrees(math.asin((r * math.cos(d) - R_MARS) / distance))
        out.append({'offset_deg': offset, 'distance_km': distance, 'elevation_deg': elevation,
                    'spot_m': {str(D): spot_m(distance, D, a['wavelength_um']) for D in [2.0, 10.0]},
                    'covers_night': offset > shadow_half and offset < horizon_half})
    return {'altitude_km': r - R_MARS, 'shadow_half_deg': shadow_half, 'horizon_half_deg': horizon_half,
            'satellites': out}


def build_report():
    a = ASSUMPTIONS
    rings = [polar_ring(h, a) for h in a['polar_altitudes_km']]
    design = next(ring for ring in rings if ring['altitude_km'] == a['design_altitude_km'])
    per_satellite_kw = a['laser_input_kw'] * a['link_efficiency']
    night_battery = lambda hours: [hours / (a['usable_share_night'] * wh / 1000) for wh in a['pack_wh_per_kg']]
    mars_night_h = MARS_DAY_H / 2
    moon_threshold = R_MOON * (math.sqrt(2) - 1)
    mars_threshold = R_MARS * (math.sqrt(2) - 1)
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Numbers quoted on part two, page 03 (the Moon, then Mars), Fig. 13 and its notes',
        'assumptions': a,
        'moon': {
            'sun_tilt_deg': SUN_TILT_MOON,
            'polar_rings': rings,
            'design': design,
            'delivered_kw_per_satellite_overhead': per_satellite_kw,
            'design_delivered_kw_two_overhead': 2 * per_satellite_kw,
            'design_delivered_kw_two_overhead_store_and_spend': 2 * per_satellite_kw * design['store_and_spend_gain'],
            'night_battery_kg_per_kw': night_battery(a['lunar_night_hours']),
            'lowest_orbit_for_midnight_km': moon_threshold,
            'beam_from_earth_orbit_spot_m': {str(D): spot_m(MOON_DISTANCE_KM, D, a['wavelength_um']) for D in [0.5, 10.0]},
            'light_time_s': MOON_DISTANCE_KM / C_KM_S,
        },
        'mars': {
            'sunlight_share_of_earth': MARS_IRRADIANCE / EARTH_IRRADIANCE,
            'panel_area_per_watt_vs_earth': EARTH_IRRADIANCE / MARS_IRRADIANCE,
            'night_h': mars_night_h,
            'night_battery_kg_per_kw': night_battery(mars_night_h),
            'night_ratio_moon_to_mars': a['lunar_night_hours'] / mars_night_h,
            'lowest_orbit_for_midnight_km': mars_threshold,
            'hover': mars_hover(a),
            'dust_transmission_straight_down': {str(t): math.exp(-t) for t in a['dust_optical_depths']},
            'light_time_min': [d / C_KM_S / 60 for d in MARS_DISTANCE_KM],
        },
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--write', action='store_true')
    args = parser.parse_args()
    payload = json.dumps(build_report(), indent=2, ensure_ascii=False) + '\n'
    script = Path(__file__).resolve()
    root = script.parents[1] if script.parent.name == 'scripts' else script.parents[2]
    if args.write:
        output = root / 'public' / 'research'
        output.mkdir(parents=True, exist_ok=True)
        (output / 'moon-mars-model.json').write_text(payload)
        target = output / 'moon-mars-numbers.py'
        if target.resolve() != script:
            shutil.copyfile(script, target)
    print(payload)


if __name__ == '__main__':
    main()
