#!/usr/bin/env python3
"""Page 8: an illustrative electrical-to-electrical link budget, not a flight design.

Run with Python's standard library to print the inputs and results as JSON.
--write publishes the JSON and this script alongside the page.
--render redraws the earlier bar-chart version of Fig. 6 (requires matplotlib). The page no
longer uses it: Fig. 6 is now drawn in the browser by src/concepts/link-cost-figure.js from the
same three efficiencies, so change them in both places.
No measured ground efficiency is reused as an assumed orbital-hop efficiency.
"""
import argparse
import json
import math
from pathlib import Path
import shutil

SIGMA = 5.670374419e-8  # W m^-2 K^-4; NIST, 2022 CODATA
ASSUMPTIONS = {
    'delivered_kw': 1.0,
    'laser_efficiency': 0.5,
    'capture_efficiency': 0.8,
    'receiver_efficiency': 0.5,
    'emissivity': 0.85,
    'radiator_temperatures_k': [300, 400],
}


def positive(value, name):
    if not math.isfinite(value) or value <= 0:
        raise ValueError(f'{name} must be finite and positive')
    return value


def fraction(value, name):
    positive(value, name)
    if value > 1:
        raise ValueError(f'{name} must not exceed one')
    return value


def link_budget(delivered_kw, laser_efficiency, capture_efficiency, receiver_efficiency):
    """Work backwards from useful receiver electricity; all powers are kW."""
    positive(delivered_kw, 'delivered_kw')
    laser = fraction(laser_efficiency, 'laser_efficiency')
    capture = fraction(capture_efficiency, 'capture_efficiency')
    receiver = fraction(receiver_efficiency, 'receiver_efficiency')
    captured_kw = delivered_kw / receiver
    emitted_kw = captured_kw / capture
    input_kw = emitted_kw / laser
    return {
        'input_kw': input_kw,
        'emitted_kw': emitted_kw,
        'captured_kw': captured_kw,
        'delivered_kw': delivered_kw,
        'hop_efficiency': laser * capture * receiver,
        'transmitter_heat_kw': input_kw - emitted_kw,
        'uncaptured_kw': emitted_kw - captured_kw,
        'receiver_heat_kw': captured_kw - delivered_kw,
    }


def source_for_hops(delivered_kw, hop_efficiency, hops):
    """No local generation, storage use, housekeeping, branching or unequal hops."""
    positive(delivered_kw, 'delivered_kw')
    fraction(hop_efficiency, 'hop_efficiency')
    if not isinstance(hops, int) or isinstance(hops, bool) or hops < 1:
        raise ValueError('hops must be a positive integer')
    return delivered_kw / hop_efficiency ** hops


def relay_output(received_kw, local_kw, own_load_kw, hop_efficiency):
    """Electricity at one relay bus, then a complete outgoing conversion link."""
    fraction(hop_efficiency, 'hop_efficiency')
    for value in (received_kw, local_kw, own_load_kw):
        if not math.isfinite(value) or value < 0:
            raise ValueError('bus powers must be finite and non-negative')
    return max(0.0, received_kw + local_kw - own_load_kw) * hop_efficiency


def ideal_radiator_area(heat_kw, temperature_k, emissivity):
    """Total emitting area, m². Cold-space sink; no absorbed external heat.

    This is an ideal surface balance, not deployed footprint or radiator mass.
    It excludes thermal transport, temperature gradients and blocked views.
    """
    positive(heat_kw, 'heat_kw')
    positive(temperature_k, 'temperature_k')
    fraction(emissivity, 'emissivity')
    return 1000 * heat_kw / (emissivity * SIGMA * temperature_k ** 4)


def conditional_cost_ratio(kappa, baseline_efficiency, path_efficiency, utilization):
    """An illustrative equal-lifetime/equal-source-availability cost comparison.

    kappa: all-in lifecycle cost per installed electrical source kW, network/baseline.
    utilization: fraction of otherwise available network energy sold usefully.
    Baseline use is 100%. Efficiencies share an electrical-source-bus boundary.
    Returns a ratio of costs per delivered kWh, not a dollar price.
    """
    positive(kappa, 'kappa')
    for value, name in [(baseline_efficiency, 'baseline_efficiency'),
                        (path_efficiency, 'path_efficiency'), (utilization, 'utilization')]:
        fraction(value, name)
    return kappa * baseline_efficiency / (path_efficiency * utilization)


def build_report():
    a = ASSUMPTIONS
    budget = link_budget(a['delivered_kw'], a['laser_efficiency'],
                         a['capture_efficiency'], a['receiver_efficiency'])
    # This audits the old range's required inputs; it does not endorse that range.
    old_ratio_requirements = []
    baseline_assumed = 0.9
    for use in [1.0, 0.3]:
        old_ratio_requirements.append({
            'utilization_assumed': use,
            'baseline_efficiency_assumed': baseline_assumed,
            'kappa_required_for_13x': 13 * budget['hop_efficiency'] * use / baseline_assumed,
            'kappa_required_for_17x': 17 * budget['hop_efficiency'] * use / baseline_assumed,
        })
    return {
        'status': 'Calculated, unreviewed',
        'scope': 'Illustrative electrical regeneration; not an STES specification',
        'assumptions': a,
        'one_link': budget,
        'no_top_up': [{'hops': n, 'source_kw': source_for_hops(1, budget['hop_efficiency'], n),
                       'delivered_kw': 1} for n in [1, 2, 3]],
        'local_top_up': {'received_kw': 1, 'added_kw': 4, 'own_load_kw': 0,
                         'outgoing_delivered_kw': relay_output(1, 4, 0, budget['hop_efficiency'])},
        'ideal_radiator': [{'temperature_k': t,
                            'transmitter_area_m2': ideal_radiator_area(budget['transmitter_heat_kw'], t, a['emissivity']),
                            'receiver_area_m2': ideal_radiator_area(budget['receiver_heat_kw'], t, a['emissivity'])}
                           for t in a['radiator_temperatures_k']],
        'measured_reference': {
            'status': 'Demonstrated; ground experiment, 1 km',
            'laser_source_optical_w': 1035,
            'receiver_electrical_w': 152,
            'optical_to_electrical_ratio': 152 / 1035,
            'electrical_input_to_laser_w': None,
            'source': 'https://doi.org/10.1049/ell2.70379',
        },
        'mass_per_hop_kg': None,
        'cost_per_delivered_kwh': None,
        'legacy_13_17x_audit': {
            'status': 'Not established: no documented all-in hardware cost or utilization inputs',
            'conditional_required_inputs': old_ratio_requirements,
            'note': 'These are algebraic requirements, not cost estimates or quotations.',
        },
        'exclusions': ['housekeeping', 'storage losses', 'transmitter/receiver thermal transport',
                       'external absorbed heat', 'flight sizing margins', 'mission availability',
                       'hardware and launch cost quotations'],
    }


def render_figures(report, folder):
    import matplotlib
    matplotlib.use('Agg')
    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties
    from matplotlib.patches import Rectangle
    plt.rcParams.update({'svg.fonttype': 'none', 'svg.hashsalt': 'stes-link-budget',
                         'font.family': ['Arial', 'Helvetica', 'DejaVu Sans', 'sans-serif'],
                         'axes.unicode_minus': False})
    navy, ink, muted, line = '#173657', '#52656b', '#708187', '#c7cecb'
    serif = FontProperties(family=['Georgia', 'Times New Roman', 'serif'])
    b = report['one_link']
    a = report['assumptions']
    powers = [b['input_kw'], b['emitted_kw'], b['captured_kw'], b['delivered_kw']]
    maximum = max(powers)
    names = ['Electrical input', 'Laser light', 'Captured light', 'Usable electricity']
    notes = ['At the transmitter', f"{a['laser_efficiency']:.0%} laser efficiency",
             f"{a['capture_efficiency']:.0%} captured", f"{a['receiver_efficiency']:.0%} receiver efficiency"]
    loss_notes = [f"{b['transmitter_heat_kw']:g} kW → heat", f"{b['uncaptured_kw']:g} kW → uncaptured",
                  f"{b['receiver_heat_kw']:g} kW → heat"]
    folder.mkdir(parents=True, exist_ok=True)
    for mobile in [False, True]:
        fig = plt.figure(figsize=(5, 4.75) if mobile else (12, 3.8), facecolor='none')
        ax = fig.add_axes([0.02, 0.01, 0.96, 0.98])
        ax.set_axis_off()
        if mobile:
            ax.set_xlim(0, maximum * 1.08); ax.set_ylim(-0.55, 4)
            for i, power in enumerate(powers):
                y = 3.45 - i * 1.02
                ax.text(0, y + .27, names[i], color=navy, size=12, va='bottom')
                ax.text(maximum * 1.05, y + .27, f'{power:g} kW', color=navy, size=16,
                        fontproperties=serif, va='bottom', ha='right')
                ax.add_patch(Rectangle((0, y), maximum, .13, facecolor='#e4e8e4', linewidth=0))
                ax.add_patch(Rectangle((0, y), power, .13, facecolor=navy, alpha=1 - i * .15, linewidth=0))
                ax.text(0, y - .15, notes[i] + (' · assumed' if i else ''),
                        color=ink, size=10.4, va='top')
        else:
            ax.set_xlim(-.75, 3.75); ax.set_ylim(-maximum * .3, maximum * 1.22)
            for i, power in enumerate(powers):
                ax.plot([i - .30, i + .30], [0, 0], color=line, lw=.7)
                ax.add_patch(Rectangle((i - .18, 0), .36, power, facecolor=navy,
                                       alpha=1 - i * .15, linewidth=0))
                ax.text(i, power + maximum * .044, f'{power:g} kW', color=navy,
                        fontproperties=serif, size=23, ha='center', va='bottom')
                ax.text(i, -maximum * .064, names[i], color=navy, size=11, ha='center', va='top')
                ax.text(i, -maximum * .166, notes[i], color=ink, size=9.3, ha='center', va='top')
            for i, text in enumerate(loss_notes):
                ax.text(i + .5, maximum * 1.176, text, color=muted, size=9.2, ha='center', va='center')
                ax.plot([i + .5, i + .5], [maximum * 1.114, maximum * 1.076], color=line, lw=.7)
        stem = 'link-cost-budget-mobile' if mobile else 'link-cost-budget'
        fig.savefig(folder / f'{stem}.svg', transparent=True, metadata={'Date': None})
        if not mobile:
            fig.savefig(folder / f'{stem}.pdf', transparent=True, metadata={'CreationDate': None})
            fig.savefig(folder / f'{stem}.png', transparent=False, facecolor='#f7f4eb', dpi=140)
        plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--write', action='store_true')
    parser.add_argument('--render', action='store_true')
    args = parser.parse_args()
    report = build_report()
    payload = json.dumps(report, indent=2, ensure_ascii=False) + '\n'
    script = Path(__file__).resolve()
    if script.parent.name == 'scripts':
        root = script.parents[1]
    elif script.parent.name == 'research' and script.parents[1].name == 'public':
        root = script.parents[2]
    else:
        root = Path.cwd()
    if args.write:
        output = root / 'public' / 'research'
        output.mkdir(parents=True, exist_ok=True)
        (output / 'link-cost-model.json').write_text(payload)
        target = output / 'link-cost-numbers.py'
        if target.resolve() != Path(__file__).resolve():
            shutil.copyfile(__file__, target)
    if args.render:
        render_figures(report, root / 'public' / 'images' / 'research')
    print(payload)


if __name__ == '__main__':
    main()
