"""Lecture 17, the best-range speed of a jet in a wind: the fuel per unit ground distance is D/(V - V_w), the slope of a
line from the point (V_w, 0) to the drag curve, least for the tangent (flight.performance.best_range_u_wind). Headwind
and tailwind of 0.4 V*. Writes img/fig-17-wind.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import performance as PF

U = np.linspace(0.3, 2.6, 300)
CASES = [(0.0, INK, "still air"), (0.4, MAROON, "headwind $0.4V^*$"), (-0.4, GREEN, "tailwind $0.4V^*$")]
BEST = {w: PF.best_range_u_wind(w) for w, _, _ in CASES}

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    ax.plot(U, PF.drag_ratio(U), color=BLUE, lw=2.8, label="drag $D/D^*$")
    for w, c, lab in CASES:
        ub = BEST[w]
        slope = PF.drag_ratio(ub) / (ub - w)
        x = np.array([w, 2.5])
        ax.plot(x, slope * (x - w), color=c, lw=1.8, ls="--")
        ax.plot(ub, PF.drag_ratio(ub), "o", color=c, ms=9)
        ax.plot(w, 0, "s", color=c, ms=7, clip_on=False)
        ax.text(1.75, {0.0: 0.62, 0.4: 0.42, -0.4: 0.22}[w], f"{lab}: best $u={ub:.2f}$", color=c, fontsize=12)
    ax.set_xlim(-0.5, 2.6); ax.set_ylim(0, 3)
    ax.set_xlabel("$u=V/V^*$ (squares: the wind speed)"); ax.set_ylabel("$D/D^*$")
    ax.legend(frameon=False, fontsize=12, loc="upper left")
    despine(ax)
    save(fig, "fig-17-wind")
