#!/usr/bin/env python3
"""Page 9: how a Chain powers a customer, worked through on an illustrative ring.

Every number on page 9 comes from this script (Python standard library only).
--write publishes the JSON and a copy of this script alongside the page.
The ring of 12 satellites is drawn for clarity; it is not a sized constellation.
Nothing here is measured: the link and battery figures are the assumptions of pages 7 and 8.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

MU = 398600.4418          # km^3 s^-2, Earth's gravitational parameter
R_EARTH = 6371.0          # km, mean radius
SIGMA = 5.670374419e-8    # W m^-2 K^-4; NIST, 2022 CODATA (source 9)

ASSUMPTIONS = {
    'network_altitude_km': 1000,           # the ring of Fig. 5
    'customer_altitude_km': 550,           # a common Earth-observation altitude
    'satellites': 12,                      # drawn for clarity, not sized
    'first_satellite_deg': 15,             # puts the customer between two satellites
    'beam_floor_km': 100,                  # a beam stays at least this far above the ground
    'link_efficiency': 0.2,                # page 8: 50% laser x 80% capture x 50% receiver
    'receiver_efficiency': 0.5,            # page 8
    'delivered_per_link_kw': 1.0,          # page 8
    'battery_return': 0.9,                 # page 7: share of stored energy given back
    '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
    'emissivity': 0.85,                    # page 8
    'radiator_temperatures_k': [300, 400], # page 8
    'wavelength_um': 1.0,                  # near-infrared, a round number
    'apertures_m': [0.5, 2.0],
    'ring_sizes': [12, 24, 48],
    'network_altitudes_km': [600, 1000, 1500, 2000, 4000, 8000],
}


def orbit(altitude_km):
    """Circular orbit with the Sun in its plane (the longest shadow, as on page 7)."""
    r = R_EARTH + altitude_km
    period = 2 * math.pi * math.sqrt(r ** 3 / MU) / 60
    half = math.asin(R_EARTH / r)
    return {'radius_km': r, 'period_min': period, 'shadow_half_angle_deg': math.degrees(half),
            'shadow_share': half / math.pi, 'shadow_min': period * half / math.pi}


def reach_deg(r1, r2, floor_km):
    """Largest angle between two craft whose straight beam stays above the floor."""
    rb = R_EARTH + floor_km
    if min(r1, r2) <= rb:
        raise ValueError('both craft must orbit above the beam floor')
    return math.degrees(math.acos(rb / r1) + math.acos(rb / r2))


def distance_km(r1, r2, angle_deg):
    return math.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * math.cos(math.radians(angle_deg)))


def spot_m(distance, aperture_m, wavelength_um):
    """Page 5's first-dark-ring diameter, 2.44 λ L / D."""
    return 2.44 * wavelength_um * 1e-6 * distance * 1e3 / aperture_m


def wrap(angle):
    return (angle + 180) % 360 - 180


def ring(a):
    """Angles are measured from the anti-Sun direction, where the customer sits."""
    net, cus = orbit(a['network_altitude_km']), orbit(a['customer_altitude_km'])
    rn, rc = net['radius_km'], cus['radius_km']
    to_customer = reach_deg(rn, rc, a['beam_floor_km'])
    between = reach_deg(rn, rn, a['beam_floor_km'])
    step = 360 / a['satellites']
    satellites = []
    for i in range(a['satellites']):
        angle = wrap(a['first_satellite_deg'] + i * step)
        dark = abs(angle) < net['shadow_half_angle_deg']
        satellites.append({'angle_deg': angle, 'in_shadow': dark,
                           'reaches_customer': abs(angle) <= to_customer,
                           'distance_to_customer_km': distance_km(rn, rc, angle)})
    feeding = [s for s in satellites if s['reaches_customer']]
    relays = []
    for s in satellites:
        if s['in_shadow'] or s['reaches_customer']:
            continue
        for t in feeding:
            gap = abs(wrap(s['angle_deg'] - t['angle_deg']))
            if gap <= between and gap <= step + 1e-9:
                relays.append({'from_deg': s['angle_deg'], 'to_deg': t['angle_deg'],
                               'distance_km': distance_km(rn, rn, gap)})
    return {'network': net, 'customer': cus, 'reach_to_customer_deg': to_customer,
            'reach_between_satellites_deg': between, 'neighbour_km': distance_km(rn, rn, step),
            'satellites': satellites, 'feeding_count': len(feeding),
            'feeding_in_sunlight': sum(not s['in_shadow'] for s in feeding),
            'relays_into_shadow': relays}


def several_beams(a, beams):
    delivered = beams * a['delivered_per_link_kw']
    heat = delivered / a['receiver_efficiency'] - delivered
    return {'beams': beams, 'delivered_kw': delivered, 'receiver_heat_kw': heat,
            'ideal_radiator_m2': {str(t): 1000 * heat / (a['emissivity'] * SIGMA * t ** 4)
                                  for t in a['radiator_temperatures_k']}}


def battery(a, net):
    """One satellite sending a full link from its battery for its whole time in shadow."""
    laser_kw = a['delivered_per_link_kw'] / a['link_efficiency']
    kwh = laser_kw * net['shadow_min'] / 60
    low_wh, high_wh = a['pack_wh_per_kg']
    low_use, high_use = a['usable_share_low_orbit']
    sun_min = net['period_min'] - net['shadow_min']
    return {'laser_input_kw': laser_kw, 'drawn_kwh': kwh,
            'pack_kg': [1000 * kwh / (high_use * high_wh), 1000 * kwh / (low_use * low_wh)],
            'recharge_kwh': kwh / a['battery_return'],
            'recharge_extra_array_kw': kwh / a['battery_return'] / (sun_min / 60)}


def routes(a):
    """Panel electricity, and battery energy, per kWh delivered to the customer."""
    link, store = a['link_efficiency'], a['battery_return']
    per = 1 / link                     # electricity into one link per kWh out of it
    return [
        {'route': 'one link from a satellite in sunlight', 'panel_kwh': per, 'battery_kwh': 0},
        {'route': 'battery, then one link', 'panel_kwh': per / store, 'battery_kwh': per},
        {'route': 'relay from sunlight, nothing added', 'panel_kwh': per ** 2, 'battery_kwh': 0},
        {'route': 'relay from sunlight, topped up from its battery',
         'panel_kwh': per + (per - 1) / store, 'battery_kwh': per - 1},
    ]


def altitude_table(a):
    rc = R_EARTH + a['customer_altitude_km']
    rows = []
    for h in a['network_altitudes_km']:
        net = orbit(h)
        reach = reach_deg(net['radius_km'], rc, a['beam_floor_km'])
        edge = net['shadow_half_angle_deg']
        rows.append({'network_altitude_km': h, 'shadow_half_angle_deg': edge, 'reach_deg': reach,
                     'sunlit_satellite_reaches_mid_shadow': reach > edge,
                     'distance_from_shadow_edge_km': distance_km(net['radius_km'], rc, edge) if reach > edge else None})
    # The altitude above which a satellite just outside the shadow can see the customer.
    lo, hi = a['customer_altitude_km'] + 1, 20000.0
    for _ in range(80):
        mid = (lo + hi) / 2
        net = orbit(mid)
        if reach_deg(net['radius_km'], rc, a['beam_floor_km']) > net['shadow_half_angle_deg']:
            hi = mid
        else:
            lo = mid
    return {'rows': rows, 'crossover_altitude_km': hi}


def ring_sizes(a):
    net = orbit(a['network_altitude_km'])
    rn, rc = net['radius_km'], R_EARTH + a['customer_altitude_km']
    reach = reach_deg(rn, rc, a['beam_floor_km'])
    rows = []
    for n in a['ring_sizes']:
        gap = distance_km(rn, rn, 360 / n)
        step = 360 / n
        # Count satellites within reach of a customer placed between two of them.
        count = sum(abs(wrap(step / 2 + i * step)) <= reach for i in range(n))
        rows.append({'satellites': n, 'neighbour_km': gap, 'in_reach_of_customer': count,
                     'spot_m': {str(d): spot_m(gap, d, a['wavelength_um']) for d in a['apertures_m']}})
    return rows


def build_report():
    a = ASSUMPTIONS
    example = ring(a)
    far = max(s['distance_to_customer_km'] for s in example['satellites'] if s['reaches_customer'])
    near = min(s['distance_to_customer_km'] for s in example['satellites'])
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Illustrative ring; not a constellation design or measured performance',
        'assumptions': a,
        'ring': example,
        'several_beams': several_beams(a, example['feeding_count']),
        'battery_per_shadowed_sender': battery(a, example['network']),
        'routes_per_kwh_delivered': routes(a),
        'network_altitude_vs_reach': altitude_table(a),
        'ring_sizes': ring_sizes(a),
        'example_links_km': {'nearest_to_customer': near, 'farthest_feeding': far,
                             'relay': example['relays_into_shadow'][0]['distance_km'] if example['relays_into_shadow'] else None},
        'example_spots_m': {str(d): {'nearest': spot_m(near, d, a['wavelength_um']), 'farthest': spot_m(far, d, a['wavelength_um'])}
                            for d in a['apertures_m']},
        'balance': 'sunlight collected = delivered + link heat and spill + battery losses + own loads',
    }


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


if __name__ == '__main__':
    main()
