"""Lecture 12: the pressure round a NACA 2412 section at -8, 4 and 10 degrees in inviscid, incompressible flow
(flight.panel, Hess-Smith). Arrows: pointing away from the surface for suction (C_p < 0), towards it for pressure
(C_p > 0); lengths in proportion to |C_p|, cut off at 3. No viscosity, so the real flow differs, most at large angles.
Writes img/fig-12-pressure.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, INK, GREY
from flight import panel as PN

X, Y = PN.naca4(0.02, 0.4, 0.12, 120)
ALPHAS = [-8.0, 4.0, 10.0]
RUNS = {a: PN.solve(X, Y, np.radians(a)) for a in ALPHAS}


def upper(a):
    """(x, cp) on the upper surface."""
    r = RUNS[a]; n = len(r["cp"]) // 2
    return r["xm"][n:], r["cp"][n:]


def lower(a):
    r = RUNS[a]; n = len(r["cp"]) // 2
    return r["xm"][:n], r["cp"][:n]


if __name__ == "__main__":
    fig, axs = plt.subplots(3, 2, figsize=(10.5, 8.4), gridspec_kw=dict(width_ratios=[1, 1.05], wspace=0.22, hspace=0.25))
    for (a_ax, p_ax), al in zip(axs, ALPHAS):
        r = RUNS[al]
        rot = np.exp(-1j * np.radians(al))
        body = (X + 1j * Y - 0.5) * rot
        a_ax.fill(body.real, body.imag, color=INK)
        for i in range(0, len(r["cp"]), 6):
            p = (r["xm"][i] + 1j * r["ym"][i] - 0.5) * rot
            nrm = r["normal"][i] * rot
            L = 0.13 * min(abs(r["cp"][i]), 3.0)
            q = p + L * nrm
            if r["cp"][i] < 0:
                a_ax.annotate("", xy=(q.real, q.imag), xytext=(p.real, p.imag), arrowprops=dict(arrowstyle="-|>", color=MAROON, lw=1.1, mutation_scale=8))
            else:
                a_ax.annotate("", xy=(p.real, p.imag), xytext=(q.real, q.imag), arrowprops=dict(arrowstyle="-|>", color=BLUE, lw=1.1, mutation_scale=8))
        a_ax.set_aspect("equal"); a_ax.set_xlim(-0.85, 0.75); a_ax.set_ylim(-0.42, 0.48); a_ax.axis("off")
        a_ax.set_title(f"{al:g}°,  $c_l$ = {r['cl']:.2f}", fontsize=12.5)
        for f, c, lab in ((upper, INK, "upper surface"), (lower, "#b45309", "lower surface")):
            x, cp = f(al); p_ax.plot(x, cp, color=c, lw=2.2, label=lab)
        p_ax.axhline(0, color=GREY, lw=0.8); p_ax.set_xlim(0, 1); p_ax.set_ylim(1.2, -5.5 if al > 5 or al < -5 else -2.0)
        p_ax.set_ylabel("$C_p$"); despine(p_ax)
    axs[0, 1].legend(frameon=False, fontsize=11, loc="upper right")
    axs[2, 1].set_xlabel("$x/c$"); axs[2, 0].text(-0.05, -0.4, "red: suction    blue: pressure above ambient", ha="center", fontsize=11)
    save(fig, "fig-12-pressure")
