"""Lecture 19: fuel burnt per kilometre by the Tejas-class model at 8500 kg and 11 km (_fighter): cruise at Mach 0.80 and
1.05 without afterburner where possible, at Mach 1.5 with it, and over the level acceleration from Mach 0.9 to 1.5.
Writes img/fig-19-fuel-per-km.png."""
import numpy as np
from _visual import plt, save, despine, MAROON, BLUE, AMBER, INK, GREY
import _fighter as F
from flight.constants import G0

H, M0 = 11000.0, F.M_REF


def per_km(M):
    """(kg of fuel per km at the starting mass, afterburner needed)."""
    ab = bool(F.needs_afterburner(F.TEJ, M, M0, H))
    return 1000.0 / (G0 * F.specific_range(F.TEJ, M, M0, H, ab)), ab


ACC = F.accelerate(F.TEJ, 0.9, 1.5, M0, H)
ACC_FUEL = float(M0 - ACC["m"][-1])                  # kg
ACC_KM = float(ACC["x"][-1]) / 1000.0
BARS = []
for lab, M in (("cruise at Mach 0.80", 0.80), ("cruise at Mach 1.05", 1.05), ("cruise at Mach 1.5", 1.5)):
    f, ab = per_km(M)
    BARS.append((lab + (", afterburner" if ab else ", no afterburner"), f, AMBER if ab else BLUE))
BARS.append(("accelerating from Mach 0.9 to 1.5", ACC_FUEL / ACC_KM, MAROON))

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10.5, 4.2))
    for i, (lab, f, c) in enumerate(BARS):
        y = len(BARS) - 1 - i
        ax.barh(y, f, color=c, height=0.62)
        extra = f"  ({ACC_FUEL:.0f} kg over {ACC_KM:.0f} km)" if i == 3 else f"  ({f / BARS[0][1]:.1f} ×)"
        ax.text(f, y, f" {f:.1f}" + extra, va="center", fontsize=11.5)
    ax.set_yticks(range(len(BARS)), [b[0] for b in BARS][::-1], fontsize=11.5)
    ax.set_xlim(0, 1.7 * max(b[1] for b in BARS)); ax.set_xlabel("fuel per kilometre (kg)")
    despine(ax)
    save(fig, "fig-19-fuel-per-km")
