"""Lecture 17: the best-range speed of a jet against the wind, in units of V* (flight.performance.best_range_u_wind),
and the ground distance per unit fuel lost by a pilot who keeps the still-air speed. Writes img/fig-17-wind-rule.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import performance as PF

W = np.linspace(-0.5, 0.5, 101)          # headwind / V*; negative is a tailwind
U_STILL = PF.best_range_u_wind(0.0)
U_BEST = np.array([PF.best_range_u_wind(w) for w in W])


def ground_range(u, w):
    """Ground distance per unit fuel in the units V*/(c D*)."""
    return PF.specific_ground_range(u, w, 1.0, PF.drag_ratio(u))


def loss(w):
    """Fraction lost by keeping the still-air speed."""
    return 1 - ground_range(U_STILL, w) / ground_range(PF.best_range_u_wind(w), w)


LOSS = np.array([loss(w) for w in W])

if __name__ == "__main__":
    fig, (a, b) = plt.subplots(1, 2, figsize=(10.5, 4.6))
    fig.subplots_adjust(wspace=0.3)
    a.plot(W, U_BEST, color=MAROON, lw=2.8)
    for w in (-0.4, 0.0, 0.4):
        u = PF.best_range_u_wind(w)
        a.plot(w, u, "o", color=INK, ms=7); a.text(w - 0.03, u + 0.025, f"{u:.2f}", fontsize=12, ha="right")
    a.set_xlabel("headwind $V_w/V^*$ (negative: tailwind)"); a.set_ylabel("best-range $u=V/V^*$")
    b.plot(W, 100 * LOSS, color=BLUE, lw=2.8)
    for w in (-0.4, 0.4):
        b.plot(w, 100 * loss(w), "o", color=INK, ms=7)
        b.text(w + (0.03 if w < 0 else -0.03), 100 * loss(w) + 0.3, f"{100 * loss(w):.1f} %", ha="left" if w < 0 else "right", fontsize=12)
    b.set_xlabel("headwind $V_w/V^*$"); b.set_ylabel("distance lost by ignoring\nthe wind (%)")
    b.set_ylim(0, 1.25 * 100 * LOSS.max())
    for ax in (a, b):
        ax.set_xlim(-0.52, 0.52); ax.axvline(0, color=GREY, lw=0.8); despine(ax)
    save(fig, "fig-17-wind-rule")
