#!/usr/bin/env python3
"""Page 11: what more power could buy a customer, and when sharing a supply pays.

Every number on page 11 comes from this script (Python standard library only).
--write publishes the JSON and a copy of this script alongside the page.
The customer is illustrative: a 1 kW satellite (NASA's reference value for average mission
power, source 1) with a 3 kW payload. The sharing model assumes independent peaks and
compares installed power only. Nothing here is measured.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

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

ASSUMPTIONS = {
    'orbit_altitude_km': 550,
    'average_supply_kw': 1.0,        # source 1: "average mission power consumption of 1000 W"
    'bus_load_kw': 0.3,              # everything except the payload; our assumption
    'payload_kw': 3.0,               # a power-hungry payload when on; our assumption
    'delivered_kw': 1.0,             # supplied for the whole time in Earth's shadow
    'receiver_efficiency': 0.5,      # page 8
    'emissivity': 0.85,              # page 8
    'radiator_temperature_k': 300,   # page 8
    'link_efficiency_example': 0.2,  # page 8
    'coverage': 0.999,               # share of moments a shared supply must cover
    'sharing_cases': [[10, 0.2], [100, 0.1], [100, 0.2], [100, 0.5], [1000, 0.2]],
}


def orbit(altitude_km):
    r = R_EARTH + altitude_km
    period = 2 * math.pi * math.sqrt(r ** 3 / MU_EARTH) / 60
    return {'period_min': period, 'shadow_min': period * math.asin(R_EARTH / r) / math.pi}


def duty(a):
    """Payload minutes per orbit on the customer's own energy, and with delivered power."""
    o = orbit(a['orbit_altitude_km'])
    spare_kw = a['average_supply_kw'] - a['bus_load_kw']
    own = spare_kw * o['period_min'] / a['payload_kw']
    added = a['delivered_kw'] * o['shadow_min'] / a['payload_kw']
    per_day = 24 * 60 / o['period_min']
    return {**o, 'own_min': own, 'added_min': added, 'with_min': own + added,
            'own_share': own / o['period_min'], 'with_share': (own + added) / o['period_min'],
            'gain': added / own, 'delivered_kwh_per_orbit': a['delivered_kw'] * o['shadow_min'] / 60,
            'own_h_per_day': own * per_day / 60, 'with_h_per_day': (own + added) * per_day / 60,
            'own_arc_deg': 360 * own / o['period_min'], 'added_arc_deg': 360 * added / o['period_min']}


def binomial_quantile(n, p, q):
    """Smallest k with P(X <= k) >= q for X ~ Binomial(n, p)."""
    total, log_p, log_q = 0.0, math.log(p), math.log1p(-p)
    for k in range(n + 1):
        total += math.exp(math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * log_p + (n - k) * log_q)
        if total >= q:
            return k
    return n


def sharing(a):
    """Shared supply as a share of the customers' summed peaks. Delivering capacity C through
    links of efficiency η needs C/η installed, so sharing saves installed power only if η > C/ΣP."""
    rows = []
    for n, f in a['sharing_cases']:
        k = binomial_quantile(n, f, a['coverage'])
        rows.append({'customers': n, 'peak_share': f, 'peaking_at_once': k, 'shared_share': k / n,
                     'break_even_link_efficiency': k / n})
    return rows


def build_report():
    a = ASSUMPTIONS
    heat_kw = a['delivered_kw'] * (1 / a['receiver_efficiency'] - 1)
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Illustrative customer and statistics; not a market study or measured performance',
        'assumptions': a,
        'duty_cycle': duty(a),
        'sharing': sharing(a),
        'receiver_heat_kw': heat_kw,
        'ideal_radiator_m2': 1000 * heat_kw / (a['emissivity'] * SIGMA * a['radiator_temperature_k'] ** 4),
    }


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


if __name__ == '__main__':
    main()
