#!/usr/bin/env python3
"""Page 13: who would pay for delivered power. The numbers behind Table 1.

Every number in Table 1 comes from this script (Python standard library only), or is
carried over from the scripts of pages 10 and 11 and marked as such below.
--write publishes the JSON and a copy of this script alongside the page.
The ranking itself is a judgment, not a calculation; see the page's notes.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

R_EARTH = 6371.0                  # km, mean radius
GEO_RADIUS_KM = 42164.0           # geostationary orbit radius
SIDEREAL_DAY_H = 23.9345
OBLIQUITY_DEG = 23.44             # tilt of Earth's axis
YEAR_DAYS = 365.25

ASSUMPTIONS = {
    # Carried over from page 10 (opportunity-numbers.py), 1 kW through the shadow or the night.
    'lunar_night_battery_kg_per_kw': [2212.5, 4425.0],
    'low_orbit_eclipse_battery_kg_per_kw': [7.27, 30.44],
    # Carried over from page 11 (more-power-numbers.py).
    'payload_time_gain': 0.532,
    # NASA NSSDCA Mars Fact Sheet, last updated 19 May 2025 (source 12).
    'mars_solar_irradiance_w_m2': 586.2,
    'earth_solar_irradiance_w_m2': 1361.0,
    'mars_length_of_day_h': 24.6597,
}


def geostationary():
    """Eclipses at geostationary height, with a cylindrical shadow (the penumbra adds a little)."""
    half = math.asin(R_EARTH / GEO_RADIUS_KM)
    longest_min = 2 * half / (2 * math.pi) * SIDEREAL_DAY_H * 60
    # Eclipses happen only while the Sun's declination is within the shadow's half-angle,
    # which happens around each equinox.
    longitude = math.asin(math.sin(half) / math.sin(math.radians(OBLIQUITY_DEG)))
    season_days = 2 * longitude / (2 * math.pi) * YEAR_DAYS
    return {'shadow_half_angle_deg': math.degrees(half), 'longest_eclipse_min': longest_min,
            'season_days': season_days, 'eclipse_days_per_year': 2 * season_days}


def mars(a):
    share = a['mars_solar_irradiance_w_m2'] / a['earth_solar_irradiance_w_m2']
    return {'sunlight_share_of_earth': share, 'night_at_equinox_h': a['mars_length_of_day_h'] / 2}


def build_report():
    a = ASSUMPTIONS
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Numbers quoted in Table 1; the ranking is a judgment',
        'assumptions': a,
        'geostationary': geostationary(),
        'mars': mars(a),
        'lunar_night_battery_t_per_kw': [kg / 1000 for kg in a['lunar_night_battery_kg_per_kw']],
        'low_orbit_eclipse_battery_kg_per_kw': a['low_orbit_eclipse_battery_kg_per_kw'],
        'payload_time_gain': a['payload_time_gain'],
    }


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


if __name__ == '__main__':
    main()
