"""Lecture 35: the share of the weight that lift must carry to hold a nearly level path, 1 - u with u = V^2/(g r),
against speed, with speeds from earlier lectures marked. Writes img/fig-35-balance.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import entry as E
from flight.constants import MU, R_EARTH

# (label, speed m/s, height m): representative speeds of Lecture 6, and the entry speed of CARE (Lecture 33)
VEHICLES = [("glider", 40.0, 1e3), ("airliner", 250.0, 11e3), ("Mach 2 fighter", 590.0, 11e3), ("CARE at entry", 5300.0, 80e3),
            ("orbit at 200 km", float(np.sqrt(MU / (R_EARTH + 200e3))), 200e3)]


def u_of(V, h):
    return V**2 * (R_EARTH + h) / MU


def lift_share(V, h):
    """Lift per unit mass on the equilibrium balance over local gravity: E times the glide drag over g."""
    r = R_EARTH + h
    return E.glide_deceleration(u_of(V, h), 1.0, MU / r**2) / (MU / r**2)


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 4.6))
    V = np.linspace(0, np.sqrt(MU / (R_EARTH + 80e3)), 400)
    ax.plot(V / 1e3, [lift_share(v, 80e3) for v in V], color=BLUE, lw=2.6)
    offsets = [(26, -92), (46, -62), (58, -30), (-12, -22), (-12, 14)]
    for (name, v, h), off in zip(VEHICLES, offsets):
        y = lift_share(v, h)
        ax.plot(v / 1e3, y, "o", color=MAROON, ms=8)
        ax.annotate(f"{name}", (v / 1e3, y), textcoords="offset points", xytext=off, fontsize=11,
                    ha="right" if off[0] < 0 else "left", arrowprops=dict(arrowstyle="-", color=GREY, lw=0.7))
    ax.set_xlabel("speed (km/s)"); ax.set_ylabel("lift needed / weight"); ax.set_xlim(0, 8.4); ax.set_ylim(-0.08, 1.12)
    despine(ax)
    save(fig, "fig-35-balance")
