"""Lecture 8, the temperature of the U.S. Standard Atmosphere 1976 from the ground to 86 km, with its seven layers
named and their lapse rates. The layer table and the temperatures come from the engine (flight.atmosphere.LAYERS,
ISA.state). Writes img/fig-08-temperature.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, GREEN, AMBER, INK, GREY
from flight import atmosphere as A

Z = np.linspace(0.0, 86e3, 861)
T = np.array([A.ISA.state(z)[0] for z in Z])
BANDS = [AMBER, BLUE, BLUE, BLUE, GREEN, MAROON, MAROON]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 6.4))
    tops = list(A.ISA.h_b[1:])
    for (name, hb, lam), top, c in zip(A.LAYERS, tops, BANDS):
        z0, z1 = A.geometric(hb) / 1e3, A.geometric(top) / 1e3
        ax.axhspan(z0, z1, color=c, alpha=0.07, lw=0)
        rate = "isothermal" if lam == 0 else (f"−{-lam * 1e3:.1f} K/km" if lam < 0 else f"+{lam * 1e3:.1f} K/km")
        ax.text(306, 0.5 * (z0 + z1), f"{name}: {rate}", va="center", fontsize=11, color=c)
    ax.plot(T, Z / 1e3, color=INK, lw=2.6)
    for hb, tb in zip(A.ISA.h_b, A.ISA.t_b):
        ax.plot(tb, A.geometric(hb) / 1e3, "o", color=INK, ms=5)
    ax.set_xlim(170, 400)
    ax.set_ylim(0, 88)
    ax.set_xlabel("temperature $T$ (K)")
    ax.set_ylabel("geometric altitude $z$ (km)")
    ax.set_xticks([180, 200, 220, 240, 260, 280, 300])
    despine(ax)
    save(fig, "fig-08-temperature")
