#!/usr/bin/env python3
"""Page 12: what delivered power could do for a ship flying a Corridor.

Every number on page 12 comes from this script (Python standard library only).
--write publishes the JSON and a copy of this script alongside the page.
The ship and its thrusters are illustrative: a 10-tonne electric tug climbing from a 500 km
orbit to geostationary height, with thruster figures from the STES briefing example.
The climb uses the standard low-thrust result for a slow spiral between circular orbits in one
plane: the velocity change equals the difference between the two circular speeds.
Nothing here is measured.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

MU = 398600.4418          # km^3 s^-2
R_EARTH = 6371.0          # km
G0 = 9.80665              # m s^-2
SIGMA = 5.670374419e-8    # W m^-2 K^-4 (source 9)

ASSUMPTIONS = {
    'ship_mass_kg': 10000,
    'specific_impulse_s': 3000,       # electric thrusters; briefing example
    'thruster_efficiency': 0.64,      # jet power / electrical power; briefing example
    'start_altitude_km': 500,
    'geostationary_radius_km': 42164,
    'powers_kw': [20, 100, 1000],
    'array_w_per_kg': 30,             # source 1: arrays cluster around ~30 W/kg
    'receiver_efficiency': 0.5,       # page 8
    'emissivity': 0.85,               # page 8
    'radiator_temperatures_k': [400, 600],
    'receiver_budget_share': 0.3,     # share of the ship's mass a receiver could take
}


def climb(a):
    r1 = (R_EARTH + a['start_altitude_km']) * 1e3
    r2 = a['geostationary_radius_km'] * 1e3
    mu = MU * 1e9
    v1, v2 = math.sqrt(mu / r1), math.sqrt(mu / r2)
    dv = v1 - v2
    ve = a['specific_impulse_s'] * G0
    eta = a['thruster_efficiency']
    m0 = a['ship_mass_kg']
    propellant = m0 * (1 - math.exp(-dv / ve))
    rows = []
    for p_kw in a['powers_kw']:
        p = p_kw * 1e3
        thrust = 2 * eta * p / ve
        mdot = thrust / ve
        seconds = propellant / mdot
        # Revolutions of the spiral: dθ = v³/μ dt with dv = −(T/m) dt; m taken at its mean.
        accel = thrust / (m0 - propellant / 2)
        turns = (v1 ** 4 - v2 ** 4) / (4 * mu * accel) / (2 * math.pi)
        rows.append({'power_kw': p_kw, 'thrust_n': thrust, 'days': seconds / 86400,
                     'turns_around_earth': turns,
                     'own_arrays_t': p / a['array_w_per_kg'] / 1000})
    return {'start_speed_km_s': v1 / 1e3, 'end_speed_km_s': v2 / 1e3, 'delta_v_km_s': dv / 1e3,
            'exhaust_speed_km_s': ve / 1e3, 'propellant_kg': propellant,
            'thrust_mn_per_kw': 2 * eta / ve * 1e6, 'by_power': rows}


def heat(a):
    per_mw = 1 / a['receiver_efficiency'] - 1
    areas = {str(t): 1e6 * per_mw / (a['emissivity'] * SIGMA * t ** 4) for t in a['radiator_temperatures_k']}
    return {'heat_mw_per_mw_delivered': per_mw, 'ideal_radiator_m2_per_mw': areas}


def receiver_target(a):
    """Specific power a receiver needs to bring 1 MW aboard within the mass budget."""
    budget_kg = a['ship_mass_kg'] * a['receiver_budget_share']
    return {'budget_kg': budget_kg, 'w_per_kg_for_1_mw': 1e6 / budget_kg,
            'times_arrays': 1e6 / budget_kg / a['array_w_per_kg']}


def build_report():
    a = ASSUMPTIONS
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Illustrative ship and thrusters; not a vehicle design or measured performance',
        'assumptions': a,
        'climb_to_geostationary': climb(a),
        'heat': heat(a),
        'receiver_target': receiver_target(a),
    }


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


if __name__ == '__main__':
    main()
