"""
Initial Mass Function choice and stellar mass-to-light ratio
============================================================

The Initial Mass Function (IMF) parameterizes the fraction of massive versus
low-mass stars born during star formation. Chabrier, Kroupa, and Salpeter IMFs
differ most in the high-mass end: Salpeter has more massive stars, producing
a higher M/L ratio (more mass per unit light) and harder UV continua. We vary
IMF while fixing SFH, age, and metallicity, overlaying rest-frame νL_ν to
reveal the IMF signature in the SED continuum shape and M/L.
"""

import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"

import warnings

import jax
import matplotlib.pyplot as plt
import numpy as np

import tengri
from tengri.plot import setup_style

setup_style()
warnings.filterwarnings("ignore", message=".*BakedInBackend.*")

C_AA_S = 2.998e18

IMFS = [
    ("fsps_prsc_miles_chabrier", "Chabrier"),
    ("fsps_prsc_miles_kroupa", "Kroupa"),
    ("fsps_prsc_miles_salpeter", "Salpeter"),
]

cmap = plt.get_cmap("viridis")
colors = cmap(np.linspace(0.15, 0.85, len(IMFS)))

fig, ax = plt.subplots(figsize=(6.5, 4.2))

for (ssp_name, imf_label), color in zip(IMFS, colors):
    ssp = tengri.load_ssp(ssp_name)
    model = tengri.SEDModel.build(
        ssp,
        sfh={
            "type": "tsnorm",
            "all_params": tengri.Fixed(tengri.DEFAULT),
            "peak_lbt_gyr": 3.0,
            "width_gyr": 0.2,
            "log_total_mass": 10.0,
            "skew": 0.0,
            "trunc": 13.0,
        },
        dust_attenuation={
            "law": "power_law",
            "type": "two_component",
            "all_params": tengri.Fixed(tengri.DEFAULT),
            "tau_diff": 0.0,
            "tau_bc": 0.0,
        },
        redshift=tengri.Fixed(0.01),
    )
    params = dict(model.spec.sample(jax.random.PRNGKey(0)))
    out = model.predict(params)
    wave = np.asarray(model.wavelengths)
    nu_l_nu = C_AA_S / wave * np.asarray(out.rest_sed())
    ax.loglog(wave, nu_l_nu, color=color, lw=1.4, label=imf_label)

ax.set_xlim(1000, 3e4)
ax.set_ylim(1e40, 1e43)
ax.set_xlabel(r"Rest-frame wavelength $\lambda$ [$\mathrm{\AA}$]")
ax.set_ylabel(r"$\nu L_\nu$ [erg s$^{-1}$]")

ax.legend(frameon=False, fontsize=9, title="IMF", title_fontsize=9)

fig.tight_layout()
plt.savefig("plot_imf_choice_sweep.png", dpi=150, bbox_inches="tight")
