#!/usr/bin/env python3
"""Part two, page 02: set and scheduled Corridors. The numbers behind Fig. 12.

Every number on the page comes from this script (Python standard library only).
--write publishes the JSON and a copy of this script alongside the page.

The same 24 power satellites at 1,000 km serve ships at 550 km in two ways:
  set:       in one ring, in the ships' own orbital plane, evenly spaced;
  scheduled: on the random orbits of page 12's dispatch simulation, taking turns as each ship
             passes. Page 12's 24 customers stand in for 24 ships, on the same seeds.
Reach follows page 12: the line between satellite and ship stays at least 100 km above the
ground. Being in reach is geometry only: whether a satellite has charge to spare, or is busy
with another customer, is page 12's question. Nothing here is measured.
"""
import argparse
import json
import math
from pathlib import Path
import random
import shutil

MU = 398600.4418          # km^3 s^-2, Earth's gravitational parameter
R_EARTH = 6371.0          # km, mean radius

ASSUMPTIONS = {
    'satellite_altitude_km': 1000,   # page 12
    'ship_altitude_km': 550,         # page 12's customers
    'beam_floor_km': 100,            # page 12
    'satellites': 24,                # page 12
    'ships': 24,                     # page 12's 24-customer case, each customer standing in for a ship
    'step_s': 60,                    # page 12
    'days': 2,                       # page 12
    'seeds': [1, 2, 3, 4],           # page 12
    'set_ring_sizes': [4, 8, 24],
    'wavelength_um': 1.0,            # page 9
    'aperture_m': 2.0,               # page 9
    'phasing_drop_km': 10,           # our example: how far a satellite drops to drift ahead
    'quarter_turn_deg': 90,
    'plane_change_deg': 10,
}


def reach_deg(r1, r2, floor_km):
    """Page 12: how far apart, seen from Earth's centre, two craft can be and still see each other
    along a line that stays floor_km above the ground."""
    rb = R_EARTH + floor_km
    return math.degrees(math.acos(rb / r1) + math.acos(rb / r2))


def random_orbits(rng, count, altitude_km):
    """Page 12: circular orbits with random tilt (uniform on the sphere), node and phase."""
    radius = R_EARTH + altitude_km
    rate = math.sqrt(MU / radius ** 3)    # rad/s
    orbits = []
    for _ in range(count):
        cos_i = rng.uniform(-1, 1)
        sin_i = math.sqrt(1 - cos_i ** 2)
        node = rng.uniform(0, 2 * math.pi)
        p = (math.cos(node), math.sin(node), 0.0)
        q = (-math.sin(node) * cos_i, math.cos(node) * cos_i, sin_i)
        orbits.append((p, q, rng.uniform(0, 2 * math.pi), rate, radius))
    return orbits


def unit(orbit, t):
    p, q, phase, rate, _ = orbit
    u = phase + rate * t
    c, s = math.cos(u), math.sin(u)
    return (c * p[0] + s * q[0], c * p[1] + s * q[1], c * p[2] + s * q[2])


def distance_km(r1, r2, cos_angle):
    return math.sqrt(max(0.0, r1 * r1 + r2 * r2 - 2 * r1 * r2 * cos_angle))


def spot_m(distance, a):
    """Diameter of the beam's central spot, as under Fig. 2."""
    return 2.44 * a['wavelength_um'] * 1e-6 * distance * 1e3 / a['aperture_m']


def set_ring(a):
    """Satellites evenly spaced in the ships' own plane: the angles between a ship and them are
    always evenly spread, so the number in reach and the nearest one's distance are bounded."""
    rs, rc = R_EARTH + a['satellite_altitude_km'], R_EARTH + a['ship_altitude_km']
    reach = math.radians(reach_deg(rs, rc, a['beam_floor_km']))
    rings = []
    for n in a['set_ring_sizes']:
        spacing = 2 * math.pi / n
        nearest_worst = distance_km(rs, rc, math.cos(spacing / 2))
        rings.append({'satellites': n, 'in_reach_at_least': math.floor(n * reach / math.pi + 1e-9),
                      'nearest_km': [rs - rc, nearest_worst], 'spot_at_worst_nearest_m': spot_m(nearest_worst, a)})
    return {'reach_deg': math.degrees(reach),
            'satellites_for_always': {str(k): math.ceil(k * math.pi / reach - 1e-9) for k in [1, 2, 6]},
            'rings': rings}


def percentile(values, share):
    ordered = sorted(values)
    return ordered[min(len(ordered) - 1, int(share * len(ordered)))]


def scheduled(a, set_worst_nearest):
    rs, rc = R_EARTH + a['satellite_altitude_km'], R_EARTH + a['ship_altitude_km']
    cos_reach = math.cos(math.radians(reach_deg(rs, rc, a['beam_floor_km'])))
    steps = int(a['days'] * 86400 / a['step_s'])
    counts = {}
    nearest = []
    gaps, gap_now = [], {}
    total = 0
    for seed in a['seeds']:
        rng = random.Random(seed * 1000 + a['ships'])          # page 12's 24-customer run
        sats = random_orbits(rng, a['satellites'], a['satellite_altitude_km'])
        ships = random_orbits(rng, a['ships'], a['ship_altitude_km'])
        for step in range(steps):
            t = step * a['step_s']
            su = [unit(s, t) for s in sats]
            for j, ship in enumerate(ships):
                cu = unit(ship, t)
                dots = [s[0] * cu[0] + s[1] * cu[1] + s[2] * cu[2] for s in su]
                seen = [d for d in dots if d >= cos_reach]
                counts[len(seen)] = counts.get(len(seen), 0) + 1
                total += 1
                key = (seed, j)
                if seen:
                    nearest.append(distance_km(rs, rc, max(seen)))
                    if gap_now.get(key):
                        gaps.append(gap_now[key])
                        gap_now[key] = 0
                else:
                    gap_now[key] = gap_now.get(key, 0) + 1
    gaps += [g for g in gap_now.values() if g]
    share = lambda k: sum(v for c, v in counts.items() if c >= k) / total
    median = percentile(nearest, 0.5)
    return {
        'ship_minutes': total,
        'share_with_at_least': {str(k): share(k) for k in [1, 2, 3, 6]},
        'mean_in_reach': sum(c * v for c, v in counts.items()) / total,
        'nearest_km_median': median,
        'nearest_km_90th_percentile': percentile(nearest, 0.9),
        'share_with_nearest_within_set_worst': sum(d <= set_worst_nearest for d in nearest) / total,
        'spot_at_median_nearest_m': spot_m(median, a),
        'gaps': {'count': len(gaps), 'longest_min': max(gaps) * a['step_s'] / 60 if gaps else 0,
                 'mean_min': (sum(gaps) / len(gaps)) * a['step_s'] / 60 if gaps else 0},
    }


def moving(a):
    """Moving satellites at 1,000 km. Along the orbit: drop a little, drift ahead, climb back.
    Across orbits: turn the orbit's plane."""
    r = R_EARTH + a['satellite_altitude_km']
    v = math.sqrt(MU / r)                     # km/s
    n = math.sqrt(MU / r ** 3)                # rad/s
    drop = a['phasing_drop_km']
    drift_per_day = math.degrees(1.5 * drop / r * n * 86400)
    # Two small transfers, down and later back up, each about (v / 2)(drop / r).
    dv_round_trip_m_s = v * drop / r * 1000
    plane = math.radians(a['plane_change_deg'])
    return {
        'orbital_speed_km_s': v,
        'drift_deg_per_day': drift_per_day,
        'quarter_turn_days': a['quarter_turn_deg'] / drift_per_day,
        'phasing_dv_m_s': dv_round_trip_m_s,
        'plane_change_dv_km_s': 2 * v * math.sin(plane / 2),
    }


def build_report():
    a = ASSUMPTIONS
    ring = set_ring(a)
    set_worst = next(r for r in ring['rings'] if r['satellites'] == a['satellites'])['nearest_km'][1]
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Numbers quoted on part two, page 02 (set and scheduled Corridors) and Fig. 12',
        'assumptions': a,
        'set': ring,
        'scheduled': scheduled(a, set_worst),
        'moving': moving(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-paths-model.json').write_text(payload)
        target = output / 'corridor-paths-numbers.py'
        if target.resolve() != script:
            shutil.copyfile(script, target)
    print(payload)


if __name__ == '__main__':
    main()
