"""
Full galaxy SED with IGM absorption applied at multiple redshifts
==================================================================

A young Lyman-break galaxy SED is built once at rest frame, then
redshifted to a sequence of observed-frame epochs (``z = 1, 3, 5, 7``)
with the Inoue et al. 2014 IGM transmission stamped on top. The
characteristic spectral signatures move with redshift:

- 1216 Å Lyα → (1+z) × 1216 Å in the observed frame
- 912 Å Lyman limit dropout sweeps redward
- Cumulative Lyman forest absorption strengthens with z

This is the figure that motivates LBG dropout selection: at z ≥ 4
the u-band drops out entirely, at z ≥ 6 g goes dark, at z ≥ 8 r
goes dark.

References:

- Inoue et al. 2014, MNRAS, 442, 1805
- Steidel et al. 1996, AJ, 112, 352 (LBG dropout origins)

"""

import os

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

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.*")

REDSHIFTS = [1.0, 3.0, 5.0, 7.0]
COLORS = plt.cm.viridis(np.linspace(0.1, 0.85, len(REDSHIFTS)))

C_AA_PER_S = 2.998e18
SFH = {
    "type": "dpl",
    "all_params": tengri.Fixed(tengri.DEFAULT),
    "tau_gyr": 0.3,
    "log_total_mass": 10.0,
    "alpha": 3.0,
    "beta": 2.0,
}
DUST = {
    "law": "power_law",
    "type": "two_component",
    "all_params": tengri.Fixed(tengri.DEFAULT),
    "tau_diff": 0.1,
    "tau_bc": 0.1,
}

fig, ax = plt.subplots(figsize=(7.4, 4.8))

for z, color in zip(REDSHIFTS, COLORS):
    model = tengri.SEDModel.build(
        tengri.load_ssp(),
        sfh=SFH,
        dust_attenuation=DUST,
        igm={"type": "inoue14"},
        redshift=tengri.Fixed(z),
    )
    p = dict(model.spec.sample(jax.random.PRNGKey(0)))
    out = model.predict(p)
    wave_rest = np.asarray(model.wavelengths)
    wave_obs = wave_rest * (1.0 + z)
    nu = C_AA_PER_S / wave_obs
    nu_f_nu = nu * np.asarray(out.rest_sed())
    ax.loglog(wave_obs, nu_f_nu, color=color, lw=1.5, label=f"$z={z:g}$")

for z, color in zip(REDSHIFTS, COLORS):
    ax.axvline(912.0 * (1.0 + z), color=color, lw=0.4, ls=":", alpha=0.6)
ax.text(912 * 2, 4e29, "← Lyman break (912 Å)\n at each z", fontsize=8, color="0.4")

BANDS = {
    "u": 3543,
    "g": 4770,
    "r": 6231,
    "i": 7625,
    "z": 9134,
    "Y": 10200,
    "J": 12300,
    "H": 16400,
}
for name, lam in BANDS.items():
    ax.axvline(lam, color="0.85", lw=0.4, alpha=0.4)
    ax.text(lam, 1.5e30, name, fontsize=7, color="0.5", ha="center", va="bottom")

ax.set(
    xlim=(500, 2e4),
    ylim=(1e29, 5e32),
    xlabel=r"Observed wavelength $\lambda$ [$\mathrm{\AA}$]",
    ylabel=r"$\nu L_\nu$  [arbitrary]",
)
ax.legend(frameon=False, fontsize=8, loc="upper right")

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