#!/usr/bin/env python3
"""Page 10: where a Chain could win, and what would have to be true there.

Every number on page 10 comes from this script (Python standard library only).
--write publishes the JSON and a copy of this script alongside the page.
Battery and link inputs repeat the assumptions of pages 7-9. The Moon's radius and GM come
from NASA's Moon Fact Sheet (source 10); the 354-hour lunar night from source 4.
The geometry is a worst case: a lander on the equator at local midnight, a circular
equatorial orbit, the Sun in that plane, and a cylindrical shadow. Nothing here is measured.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

R_EARTH = 6371.0          # km, mean radius
MU_EARTH = 398600.4418    # km^3 s^-2
R_MOON = 1737.4           # km, volumetric mean radius (source 10)
MU_MOON = 4900.0          # km^3 s^-2, GM = 0.00490 x 10^6 (source 10)
SIGMA = 5.670374419e-8    # W m^-2 K^-4; NIST, 2022 CODATA (source 9)

ASSUMPTIONS = {
    'pack_wh_per_kg': [100, 200],          # page 7, inside NASA's pack range (source 1)
    'usable_share_low_orbit': [0.2, 0.4],  # page 7, our assumption
    'usable_share_lunar_night': 0.8,       # page 7, our assumption
    'low_orbit_altitudes_km': [300, 1000], # page 7's range
    'lunar_night_hours': 354,              # source 4
    'lunar_altitudes_km': [500, 1000, 1500, 3000, 5000, 10000],  # 720 km is the threshold itself
    'figure_altitude_km': 1500,            # the orbit drawn in Fig. 8
    'receiver_efficiency': 0.5,            # page 8
    'emissivity': 0.85,                    # page 8
    'radiator_temperature_k': 300,         # page 8
    'wavelength_um': 1.0,                  # page 9
    'apertures_m': [0.5, 2.0],             # page 9
}


def earth_eclipse_min(altitude_km):
    r = R_EARTH + altitude_km
    period = 2 * math.pi * math.sqrt(r ** 3 / MU_EARTH) / 60
    return period * math.asin(R_EARTH / r) / math.pi


def battery_kg(kwh, usable, wh_per_kg):
    return 1000 * kwh / (usable * wh_per_kg)


def batteries(a):
    """Batteries to carry 1 kW through the dark, for each case."""
    lo_wh, hi_wh = a['pack_wh_per_kg']
    lo_use, hi_use = a['usable_share_low_orbit']
    eclipse = [earth_eclipse_min(h) for h in a['low_orbit_altitudes_km']]
    leo_kwh = [m / 60 for m in eclipse]
    night_kwh = a['lunar_night_hours']
    night_use = a['usable_share_lunar_night']
    leo_kg = [battery_kg(min(leo_kwh), hi_use, hi_wh), battery_kg(max(leo_kwh), lo_use, lo_wh)]
    night_kg = [battery_kg(night_kwh, night_use, hi_wh), battery_kg(night_kwh, night_use, lo_wh)]
    # Like for like (same pack): energy ratio times the usable-share ratio.
    ratio = [(night_kwh / night_use) / (max(leo_kwh) / lo_use), (night_kwh / night_use) / (min(leo_kwh) / hi_use)]
    return {'low_orbit_eclipse_min': sorted(eclipse), 'low_orbit_kwh': sorted(leo_kwh), 'low_orbit_kg': leo_kg,
            'lunar_night_kwh': night_kwh, 'lunar_night_kg': night_kg, 'mass_ratio_same_pack': ratio}


def lunar_distance(r, angle):
    return math.sqrt(r ** 2 + R_MOON ** 2 - 2 * r * R_MOON * math.cos(angle))


def lunar_window(altitude_km):
    """A satellite in a circular equatorial orbit and a lander at local midnight on the equator.

    Angles run from the anti-Sun point. The satellite is in sunlight when r sin θ > R, and above the
    lander's horizon when r cos θ > R. Both hold for asin(R/r) < |θ| < acos(R/r): two windows per orbit.
    """
    r = R_MOON + altitude_km
    period_h = 2 * math.pi * math.sqrt(r ** 3 / MU_MOON) / 3600
    lo, hi = math.asin(R_MOON / r), math.acos(R_MOON / r)
    side = max(0.0, hi - lo)
    row = {'altitude_km': altitude_km, 'period_h': period_h,
           'sunlit_from_deg': math.degrees(lo), 'in_view_to_deg': math.degrees(hi),
           'window_per_orbit_min': 2 * side / (2 * math.pi) * period_h * 60,
           'share_of_orbit': 2 * side / (2 * math.pi),
           # A lower bound: windows from evenly spaced satellites would have to tile the night exactly.
           'satellites_for_steady_power_at_least': math.ceil(math.pi / side) if side > 0 else None}
    if side > 0:
        mid = (lo + hi) / 2
        row.update({'distance_km': [lunar_distance(r, lo), math.sqrt(r ** 2 - R_MOON ** 2)],
                    'distance_mid_km': lunar_distance(r, mid), 'mid_deg': math.degrees(mid)})
    return row


def spot_m(distance_km, aperture_m, wavelength_um):
    return 2.44 * wavelength_um * 1e-6 * distance_km * 1e3 / aperture_m


def build_report():
    a = ASSUMPTIONS
    cases = batteries(a)
    windows = [lunar_window(h) for h in a['lunar_altitudes_km']]
    figure = lunar_window(a['figure_altitude_km'])
    heat_kw = 1 / a['receiver_efficiency'] - 1
    radiator = 1000 * heat_kw / (a['emissivity'] * SIGMA * a['radiator_temperature_k'] ** 4)
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Worst-case geometry and sizing examples; not a mission design or measured performance',
        'assumptions': a,
        'constants': {'moon_radius_km': R_MOON, 'moon_gm_km3_s2': MU_MOON},
        'batteries_per_kw': cases,
        'lunar_threshold_altitude_km': R_MOON * (math.sqrt(2) - 1),
        'lunar_windows': windows,
        'figure_orbit': figure,
        'figure_spots_m': {str(d): spot_m(figure['distance_mid_km'], d, a['wavelength_um']) for d in a['apertures_m']},
        'heat_per_kw_delivered_kw': heat_kw,
        'ideal_radiator_m2_per_kw': radiator,
        'gates': [
            'Mass: receiver and electronics lighter than the batteries they replace',
            'Reach: links keep their efficiency over thousands of kilometres',
            'Coverage: a satellite in sunlight sees the customer whenever it needs power',
            'Heat: the receiver sheds what it does not convert',
            'Price: a delivered kWh costs less than the alternative; no cost model yet',
        ],
    }


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 / 'opportunity-model.json').write_text(payload)
        target = output / 'opportunity-numbers.py'
        if target.resolve() != script:
            shutil.copyfile(script, target)
    print(payload)


if __name__ == '__main__':
    main()
