"""Lecture 21, the HAL HJT-16 Kiran (partly estimated dataset, 4950 kg, 18.4 kN at sea level, thrust proportional to
density): the greatest rate of climb and its airspeed against altitude, the absolute ceiling (rate of climb zero) and
the service ceiling (100 ft/min, Sadraey sec. 5.6), against Sadraey's listed service ceiling of 39,375 ft (Table 5.7).
Writes img/fig-21-kiran.png."""
import numpy as np
from scipy.optimize import brentq
from _visual import plt, save, despine, MAROON, BLUE, GREY, INK
import _climb as C
from flight import performance as PF
from flight.constants import FT, G0

W = C.M_KIRAN * G0
H = np.linspace(0, 13250, 300)
ROC = np.array([C.max_roc(C.KIRAN, W, h) for h in H])
VFC = np.array([PF.fastest_climb_u(C.scales(C.KIRAN, W, h)[0]) * C.scales(C.KIRAN, W, h)[1] for h in H])
H_ABS = brentq(lambda h: C.max_roc(C.KIRAN, W, h), 10000, 16000)
H_SERVICE = brentq(lambda h: C.max_roc(C.KIRAN, W, h) - 100 * FT / 60, 10000, 16000)
SOURCED = 39375 * FT
ROC_SL = ROC[0]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 4.8))
    fig.subplots_adjust(wspace=0.3)
    a1.plot(ROC, H / 1e3, color=MAROON, lw=2.6)
    for hh, lab, ls in ((H_ABS, "absolute ceiling (model)", "-"), (H_SERVICE, "service ceiling (model)", "--"), (SOURCED, "service ceiling, Sadraey", ":")):
        a1.axhline(hh / 1e3, color=INK if ls != ":" else BLUE, lw=1.2, ls=ls, label=f"{lab}: {hh / 1e3:.2f} km")
    a1.set_xlabel("greatest rate of climb (m/s)"); a1.set_ylabel("altitude (km)"); a1.set_xlim(0, 40); a1.set_ylim(0, 14.5)
    fig.legend(frameon=False, fontsize=11, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 0.0))
    a2.plot(VFC, H / 1e3, color=BLUE, lw=2.6)
    a2.set_xlabel("airspeed of fastest climb (m/s)"); a2.set_ylim(0, 14.5)
    despine(a1); despine(a2)
    save(fig, "fig-21-kiran")
