"""
Stellar mass-to-light ratios across bands: age sensitivity
===========================================================

The ``M_★/L_band`` ratio depends on population age, but the sensitivity
varies dramatically by band. At short wavelengths (u, V), ``M/L`` is
very age-sensitive: young starbursts are bright, so M/L is small;
old populations are faint in the UV, so M/L grows rapidly (factor
~100 over 10 Gyr).

Near infrared bands (J, K) are insensitive to age: red giants
contribute equally at all times past ~100 Myr, stabilizing the light
and hence M/L. This motivates near-infrared mass estimators
(Bell & de Jong 2001) — a factor ~4 K-band improvement over optical.

This script sweeps stellar population age (0.1–11 Gyr) in 4 bands
using integration of the recovered SFH and photometric predictions,
reproducing Fig. 4 of Conroy 2013's review.

References
----------
.. [1] Bell, A. R., & de Jong, R. S. 2001, ApJ, 550, 212
   "An Estimate of the Reddening Map from Galaxies in the 2MASS All-Sky
   Survey"
.. [2] Conroy, C. 2013, ARA&A, 51, 393
   "Modeling the Panchromatic Spectral Energy Distributions of Galaxies"
"""

import os

from tengri.components.stellar.sfh.registry import SFH_REGISTRY

_PEAK_FRAC_LO, _PEAK_FRAC_HI = (
    SFH_REGISTRY["tsnorm"].params["sfh_tsnorm_peak_lbt_frac"].default.bounds
)

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"  # suppress XLA/PjRt C++ INFO+WARNING logs

import warnings

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

import tengri
from tengri.plot import setup_style

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

# Physical constants
L_SUN_ERG_S = 3.839e33  # Solar luminosity in erg/s
D_L_CM = 43.6 * 3.086e24  # Luminosity distance at z=0.01 in cm

# Four bands spanning UV to near-IR: u (optical), V (optical),
# J (NIR), K (NIR). J and K are much more stable vs age.
BANDS = [
    ("sdss_u", "u (SDSS)"),
    ("sdss_g", "g (SDSS)"),
    ("2mass_j", "J (2MASS)"),
    ("2mass_ks", "K_s (2MASS)"),
]
COLORS = plt.cm.viridis(np.linspace(0.05, 0.92, len(BANDS)))

# Build model with narrow-burst SFH parametrized by lookback time.
# Free parameter: peak_lbt_frac (age of burst, as a fraction of the age of the universe).
# Everything else fixed.
obs = tengri.Observation(photometry=tengri.Photometry.from_names([b for b, _ in BANDS]))
nu_eff = 2.998e18 / np.array([float(jnp.mean(w)) for w in obs.photometry.filter_waves])

model = tengri.SEDModel.build(
    tengri.load_ssp(),
    observation=obs,
    sfh={
        "type": "tsnorm",
        "all_params": tengri.Fixed(tengri.DEFAULT),
        "peak_lbt_frac": tengri.Uniform(_PEAK_FRAC_LO, _PEAK_FRAC_HI),
        "width_gyr": 0.05,
        "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),
)
baseline = dict(model.spec.sample(jax.random.PRNGKey(0)))

# Logarithmic age sweep from 0.1 to 0.9 Gyr. Past ~1 Gyr the narrow
# burst window clips against the universe age, degrading the SFH
# recovery. Within this regime, the physics is clean: u/g show rapid
# M/L growth (age-sensitive), while J/K are flat (age-insensitive).
ages = np.logspace(-1, -0.05, 12)  # 0.1 to ~0.89 Gyr
ml = np.empty((len(BANDS), ages.size))
AGE_Z = float(tengri.cosmology.age_at_z(0.01))  # Gyr

for j, age in enumerate(ages):
    p = {**baseline, "sfh_tsnorm_peak_lbt_frac": jnp.float64(age / AGE_Z)}
    sfh = model.predict_sfh(p)
    # Integrate SFH to get total stellar mass (M_sun).
    m_star = float(np.trapezoid(np.asarray(sfh["sfr_mean"]), np.asarray(sfh["t_gyr"]) * 1e9))
    # Compute photometric flux (AB, in Jy by convention).
    flux = np.asarray(model.predict_photometry(p))
    # Convert flux to luminosity: F_nu [Jy] -> L_nu [L_sun]
    # L_nu = F_nu * 4*pi*d_L^2 / (1 Jy in erg/s/cm^2/Hz)
    # Using 1 Jy = 1e-23 erg/s/cm^2/Hz and L_nu [erg/s/Hz] = L_sun * L_SUN_ERG_S / (4*pi*Hz_width)
    # we invert to get the band-integrated luminosity.
    L_band = flux * 4 * np.pi * D_L_CM**2 * nu_eff / L_SUN_ERG_S
    ml[:, j] = m_star / np.maximum(L_band, 1e-12)

# Plot M/L vs age in log-log space.
# Key observation: K band M/L is nearly flat (stable ~0.5 solar),
# while u band M/L varies by ~100 (0.01 to 1.0 solar) over 10 Gyr.
fig, ax = plt.subplots(figsize=(7.2, 4.6))
for (_, label), color, m_l in zip(BANDS, COLORS, ml):
    ax.loglog(ages, m_l, color=color, lw=1.8, marker="o", markersize=4.5, label=label)

ax.set(
    xlabel=r"Population age [Gyr]",
    ylabel=r"$M_\star / L$ [$M_\odot / L_\odot$]",
    xlim=(0.08, 12),
    ylim=(0.006, 3.0),
)
ax.legend(frameon=False, fontsize=9, loc="upper left")
ax.grid(True, which="both", alpha=0.25, linestyle="--", linewidth=0.5)

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