"""Lecture 19, the price of a supersonic dash for the Tejas-class model. A mission at 11 km starting at 8500 kg with
FUEL kg to spend: cruise out at the best-range Mach number on military thrust, accelerate with afterburner from that Mach
number to 1.5, dash at Mach 1.5 with afterburner, and cruise back at the best-range Mach number. The radius is found for
each dash distance (cruise legs: _fighter.cruise_fuel; acceleration: flight.performance.accelerate_level). The fuel for
take-off, climb, descent and reserves is outside FUEL. Writes img/fig-19-dash.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, INK
import _fighter as F
from _scripts import load

V, MASS, H = F.TEJ, F.M_REF, 11000.0
FUEL = 1500.0                                         # kg, an assumed fuel allowance for the mission legs
SR = load("fig-19-specific-range")
M_CRUISE = round(SR.BEST[H][0], 2)                     # best-range Mach number at 11 km
M_DASH = 1.5


X_ACC = F.accelerate(V, M_CRUISE, M_DASH, MASS, H)["x"][-1]      # ground covered while accelerating (about 37 km)


def fuel_used(radius, dash):
    """Out: cruise, then accelerate (covering X_ACC), then dash `dash` at Mach 1.5; back: dash `dash`, cruise home.
    The deceleration on the way back is taken as free."""
    m = MASS
    if dash > 0:
        m -= F.cruise_fuel(V, M_CRUISE, H, m, radius - dash - X_ACC, ab=False)
        m = F.accelerate(V, M_CRUISE, M_DASH, m, H)["m"][-1]
        m -= F.cruise_fuel(V, M_DASH, H, m, 2 * dash, ab=True)
        m -= F.cruise_fuel(V, M_CRUISE, H, m, radius - dash, ab=False)
    else:
        m -= F.cruise_fuel(V, M_CRUISE, H, m, 2 * radius, ab=False)
    return MASS - m


def radius(dash):
    lo = dash + X_ACC + 1.0 if dash > 0 else 1.0
    return brentq(lambda r: fuel_used(r, dash) - FUEL, lo, 1.5e6, xtol=1.0)


DASHES = np.arange(0.0, 40001.0, 10e3)
RADII = np.array([radius(d) for d in DASHES])
SLOPE = (RADII[-1] - RADII[1]) / (DASHES[-1] - DASHES[1])
MAX_DASH = brentq(lambda d: fuel_used(d + X_ACC, d) - FUEL, 10e3, 200e3, xtol=1.0)   # no subsonic cruise out

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.8))
    ax.plot(DASHES / 1e3, RADII / 1e3, "o-", color=MAROON, lw=2.6, ms=7)
    ax.plot([DASHES[-1] / 1e3, MAX_DASH / 1e3], [RADII[-1] / 1e3, (MAX_DASH + X_ACC) / 1e3], ":", color=MAROON, lw=2)
    ax.plot(MAX_DASH / 1e3, (MAX_DASH + X_ACC) / 1e3, "s", color=INK, ms=7)
    ax.set_xlabel("supersonic dash at Mach 1.5, each way (km)"); ax.set_ylabel("mission radius (km)")
    ax.set_ylim(0, RADII[0] / 1e3 * 1.1)
    despine(ax)
    save(fig, "fig-19-dash")
