#!/usr/bin/env python3
"""Page 12: who gets the power. A minute-by-minute dispatch simulation on random orbits.

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.

Power satellites and customers fly circular orbits with random tilts and phases; this is
not a designed constellation, which would spread its satellites more evenly. Every minute
the dispatcher matches satellites to customers they can reach. The comparison case ties
each satellite to one customer, so it can only sell while that customer is in reach.
The link, battery and receiver figures are the illustrative assumptions of pages 7 to 9.
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,         # the ring of page 9
    'customer_altitude_km': 550,           # page 9
    'beam_floor_km': 100,                  # page 9: a beam stays this far above the ground
    'satellites': 24,
    'customer_counts': [3, 6, 12, 24, 48],
    'panel_kw': 5.0,                       # array output in sunlight, after the satellite's own loads
    'laser_input_kw': 5.0,                 # page 8: 5 kW in, 1 kW delivered
    'link_efficiency': 0.2,                # page 8
    'battery_usable_kwh': 3.0,             # page 9: 2.9 kWh drawn per pass
    'battery_return': 0.9,                 # page 7
    'battery_start_share': 0.5,
    'receiver_limit_kw': 4.0,              # delivered; page 9's four 1 kW beams
    'step_s': 60,
    'days': 2,
    'seeds': [1, 2, 3, 4],
}


def reach_deg(r1, r2, floor_km):
    rb = R_EARTH + floor_km
    return math.degrees(math.acos(rb / r1) + math.acos(rb / r2))


def random_orbits(rng, count, altitude_km):
    """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 run(a, customers, seed, tied):
    """Energy flows for one fleet over the simulated days. Energies in kWh."""
    rng = random.Random(seed * 1000 + customers)
    sats = random_orbits(rng, a['satellites'], a['satellite_altitude_km'])
    custs = random_orbits(rng, customers, a['customer_altitude_km'])
    cos_reach = math.cos(math.radians(reach_deg(sats[0][4], custs[0][4], a['beam_floor_km'])))
    dt_h = a['step_s'] / 3600
    gen_step = a['panel_kw'] * dt_h
    laser_step = a['laser_input_kw'] * dt_h
    room_step = a['receiver_limit_kw'] / a['link_efficiency'] * dt_h   # laser input a receiver can take
    cap, ret = a['battery_usable_kwh'], a['battery_return']
    battery = [cap * a['battery_start_share']] * len(sats)
    start_store = sum(battery)
    shadow_limit = (R_EARTH / sats[0][4]) ** 2
    totals = {'generated': 0.0, 'sold': 0.0, 'wasted': 0.0, 'charge_loss': 0.0}
    received = [0.0] * customers
    served_steps = [0] * customers
    pair_in_reach = 0
    pair_checks = 0
    steps = int(a['days'] * 86400 / a['step_s'])
    for step in range(steps):
        t = step * a['step_s']
        su = [unit(o, t) for o in sats]
        cu = [unit(o, t) for o in custs]
        # The Sun lies along +x: a satellite is dark behind Earth, inside its cylindrical shadow.
        sunlit = [not (u[0] < 0 and 1 - u[0] ** 2 < shadow_limit) for u in su]
        gen = [gen_step if lit else 0.0 for lit in sunlit]
        avail = [min(laser_step, g + b) for g, b in zip(gen, battery)]
        if tied:
            options = []
            for j in range(customers):
                k = j % len(sats)
                d = su[k][0] * cu[j][0] + su[k][1] * cu[j][1] + su[k][2] * cu[j][2]
                options.append([k] if d >= cos_reach else [])
        else:
            options = [[k for k in range(len(sats)) if su[k][0] * cu[j][0] + su[k][1] * cu[j][1] + su[k][2] * cu[j][2] >= cos_reach]
                       for j in range(customers)]
        if customers <= len(sats):
            # How often customer j is in reach of satellite j: a check on the expected share.
            for j, opts in enumerate(options):
                pair_checks += 1
                pair_in_reach += j in opts
        # Customers with the fewest satellites in reach are served first. Each satellite sends one
        # beam; satellites in sunlight go first, then the fullest batteries.
        sent = [0.0] * len(sats)
        busy = [False] * len(sats)
        for j in sorted(range(customers), key=lambda j: len(options[j])):
            room = room_step
            for k in sorted(options[j], key=lambda k: (not sunlit[k], -battery[k])):
                if room <= 1e-12:
                    break
                if busy[k] or avail[k] <= 1e-12:
                    continue
                amount = min(avail[k], room)
                sent[k] = amount
                busy[k] = True
                room -= amount
                received[j] += amount * a['link_efficiency']
            if room < room_step - 1e-12:
                served_steps[j] += 1
        for k in range(len(sats)):
            from_gen = min(sent[k], gen[k])
            battery[k] -= sent[k] - from_gen
            spare = gen[k] - from_gen
            stored = min(spare * ret, cap - battery[k])
            battery[k] += stored
            totals['generated'] += gen[k]
            totals['sold'] += sent[k]
            totals['charge_loss'] += stored / ret - stored
            totals['wasted'] += spare - stored / ret
    totals['battery_change'] = sum(battery) - start_store
    # Energy available = sunlight collected plus whatever the batteries ran down, so the shares
    # below (sold, wasted, battery loss) add up to one.
    available = totals['generated'] - totals['battery_change']
    hours = steps * dt_h
    return {
        'totals_kwh': totals,
        'sold_share_of_generated': totals['sold'] / available,
        'wasted_share_of_generated': totals['wasted'] / available,
        'battery_loss_share': totals['charge_loss'] / available,
        'delivered_per_customer_kw': sum(received) / customers / hours,
        'customer_share_of_minutes_served': sum(served_steps) / customers / steps,
        'delivered_per_satellite_kwh_per_day': totals['sold'] * a['link_efficiency'] / len(sats) / a['days'],
        'generated_per_satellite_kwh_per_day': totals['generated'] / len(sats) / a['days'],
        'sampled_pair_in_reach_share': pair_in_reach / pair_checks if pair_checks else None,
    }


def average(runs, key):
    return sum(r[key] for r in runs) / len(runs)


def summarise(runs):
    keys = ['sold_share_of_generated', 'wasted_share_of_generated', 'battery_loss_share', 'delivered_per_customer_kw',
            'customer_share_of_minutes_served', 'delivered_per_satellite_kwh_per_day',
            'generated_per_satellite_kwh_per_day']
    out = {key: average(runs, key) for key in keys}
    out['sold_share_range'] = [min(r['sold_share_of_generated'] for r in runs), max(r['sold_share_of_generated'] for r in runs)]
    return out


def build_report():
    a = ASSUMPTIONS
    rs, rc = R_EARTH + a['satellite_altitude_km'], R_EARTH + a['customer_altitude_km']
    reach = reach_deg(rs, rc, a['beam_floor_km'])
    pair_share = (1 - math.cos(math.radians(reach))) / 2
    tied_runs = [run(a, a['satellites'], seed, tied=True) for seed in a['seeds']]
    dispatched = {}
    for m in a['customer_counts']:
        dispatched[str(m)] = summarise([run(a, m, seed, tied=False) for seed in a['seeds']])
    tied = summarise(tied_runs)
    tied['sampled_pair_in_reach_share'] = average(tied_runs, 'sampled_pair_in_reach_share')
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Random orbits and illustrative hardware; not a constellation design or measured performance',
        'assumptions': a,
        'reach_deg': reach,
        'pair_in_reach_share_expected': pair_share,
        'at_least_one_of_m_in_reach': {str(m): 1 - (1 - pair_share) ** m for m in [1, 3, 6, 12, 24, 48]},
        'tied_one_customer_each': tied,
        'dispatched_by_customer_count': dispatched,
    }


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


if __name__ == '__main__':
    main()
