"""Lecture 20, the glide footprint in a wind: the ground the Kiran model (dataset polar, 4950 kg) can reach from 3 km
with no thrust, in still air and in a steady 15 m/s wind blowing towards the east. Density held at its value at 1.5 km;
small-angle glide; turning is neglected. For each outward direction d the farthest point is flown with air heading d
at the speed to fly for the wind component along d (flight.performance.speed_to_fly with headwind -w.d); it is
t (w + V d), with t = height / sink rate. Writes img/fig-20-footprint.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import vehicle, performance as PF, atmosphere as A, aero as AE
from flight.constants import G0

K = vehicle.load("hjt-16-kiran")
W = K.gross_mass * G0
CD0, KK, S = K.aero.cd0(0.0), K.aero.k(0.0), K.aero.S
RHO = A.isa(1500.0)[2]
DH, WIND = 3000.0, np.array([15.0, 0.0])
EMAX = AE.max_lift_to_drag(CD0, KK)[1]


def sink(V):
    return PF.sink_rate_small_angle(V, W, RHO, S, CD0, KK)


def point(angle, wind):
    d = np.array([np.cos(angle), np.sin(angle)])
    V = PF.speed_to_fly(W, RHO, S, CD0, KK, headwind=-float(wind @ d))
    return DH / sink(V) * (wind + V * d), V


def reach(direction, wind):
    """Farthest ground distance in the ground direction `direction` (rad from east), over all air headings and speeds."""
    V = np.linspace(45.0, 220.0, 1400)
    t = DH / sink(V)
    g = np.array([np.cos(direction), np.sin(direction)])
    along = float(wind @ g)
    cross = float(wind @ np.array([-g[1], g[0]]))
    ok = V > abs(cross)
    return float(np.max(t[ok] * (along + np.sqrt(V[ok]**2 - cross**2))))


ANG = np.linspace(0, 2 * np.pi, 361)
CALM = np.array([point(a, np.zeros(2))[0] for a in ANG]) / 1e3
WINDY = np.array([point(a, WIND)[0] for a in ANG]) / 1e3
R_CALM = reach(0.0, np.zeros(2)) / 1e3
R_DOWN, R_UP, R_CROSS = (reach(a, WIND) / 1e3 for a in (0.0, np.pi, np.pi / 2))
V_DOWN, V_UP = point(0.0, WIND)[1], point(np.pi, WIND)[1]
FIELDS = [(-(R_UP + R_CALM) / 2, 0.0, "field A, upwind"), ((R_DOWN + R_CALM) / 2, 0.0, "field B, downwind")]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 7.2))
    ax.plot(*CALM.T, color=GREY, lw=2.2, ls="--", label="still air")
    ax.plot(*WINDY.T, color=MAROON, lw=2.8, label="15 m/s wind towards the east")
    ax.plot(0, 0, "o", color=INK, ms=9); ax.text(0, -3.2, "engine fails\nat 3 km", ha="center", va="top", fontsize=11)
    for x, y, lab in FIELDS:
        ax.plot(x, y, "s", color=BLUE, ms=11)
        ax.text(x, y + 2.2, lab, ha="center", fontsize=12, color=BLUE)
    ax.annotate("", xy=(14, 44), xytext=(-14, 44), arrowprops=dict(arrowstyle="-|>", color=INK, lw=2.2, mutation_scale=18))
    ax.text(0, 46, "wind", ha="center", fontsize=12)
    for x, txt, ha in ((-R_UP, f"{R_UP:.1f} km", "right"), (R_DOWN, f"{R_DOWN:.1f} km", "left")):
        ax.plot(x, 0, "|", color=MAROON, ms=16, mew=2.5)
        ax.text(x + (1.2 if ha == "left" else -1.2), -3.2, txt, ha=ha, va="top", fontsize=11, color=MAROON)
    ax.set_aspect("equal"); ax.set_xlim(-58, 62); ax.set_ylim(-56, 52)
    ax.set_xlabel("distance east (km)"); ax.set_ylabel("distance north (km)")
    ax.legend(frameon=False, fontsize=12, loc="lower center", ncol=2)
    despine(ax)
    save(fig, "fig-20-footprint")
