"""Lecture 9: schematic of where the westerly jet streams are found. Latitudes are rough typical values; the real jets
meander, break up, and move with the season. Writes img/fig-09-jet-streams.png."""
import numpy as np
from matplotlib.patches import Circle
from _visual import plt, save, MAROON, BLUE, INK, GREY

JETS = [(30.0, MAROON, "subtropical jet, near 30°", 1.5), (55.0, BLUE, "polar-front jet, roughly 40° to 60°,\nwith large waves", 7.0)]
TILT = np.radians(18)


def on_globe(lat, lon):
    """Orthographic view from above latitude TILT: (x, y, visible)."""
    p, l = np.radians(lat), np.radians(lon)
    x = np.cos(p) * np.sin(l)
    y = np.sin(p) * np.cos(TILT) - np.cos(p) * np.cos(l) * np.sin(TILT)
    z = np.sin(p) * np.sin(TILT) + np.cos(p) * np.cos(l) * np.cos(TILT)
    return x, y, z > 0


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.4))
    ax.add_patch(Circle((0, 0), 1.0, facecolor="#dfe7ef", edgecolor=INK, lw=1.4))
    lon = np.linspace(-110, 110, 600)
    for lat in (0.0,):
        x, y, v = on_globe(lat, lon); ax.plot(x[v], y[v], color=GREY, lw=1.2, ls="--")
    ax.text(*on_globe(-6, 0)[:2], "equator", ha="center", fontsize=11, color=INK)
    for base, c, lab, wave in JETS:
        for sign in (1, -1):
            lat = sign * (base + wave * np.sin(np.radians(4.5 * lon)))
            x, y, v = on_globe(lat, lon)
            x, y = np.where(v, x, np.nan), np.where(v, y, np.nan)
            ax.plot(x, y, color=c, lw=3.2)
            for i in (170, 430):
                if np.isfinite(x[i]) and np.isfinite(x[i + 12]):
                    ax.annotate("", xy=(x[i + 12], y[i + 12]), xytext=(x[i], y[i]), arrowprops=dict(arrowstyle="-|>", color=c, lw=2.6, mutation_scale=18))
        xx, yy, _ = on_globe(base, 62)
        ax.annotate(lab, (xx, yy), xytext=(1.2, yy + (0.22 if base > 40 else -0.05)), fontsize=12, color=c, va="center", arrowprops=dict(arrowstyle="-", color=c, lw=1))
    ax.text(1.2, -0.62, "both blow from west to east,\nin both hemispheres", fontsize=12, va="center")
    ax.set_xlim(-1.1, 2.85); ax.set_ylim(-1.08, 1.12); ax.set_aspect("equal"); ax.axis("off")
    save(fig, "fig-09-jet-streams")
