"""
Radio blocks: which q_IR calibration, and which AGN synchrotron shape
=====================================================================

The radio group is two independent choices — a star-forming block tied to the
FIR-radio correlation, and an AGN block — so this compares them one at a time
on the same galaxy (a constant-SFH galaxy with log total mass 10.5 at z = 0.05).

(Left) The four star-forming blocks, with AGN radio off, normalized to
``bell2003``. The ``bell2003_split`` curve is the AGNfitter-rX split and is not
quoted. ``delvecchio2021`` is 0.88, 1.09 and 1.21 times ``bell2003`` at
150 MHz, 1.4 GHz and 10 GHz. ``mccheyne2022`` is 0.78, 1.17 and 1.48 times it
at the same frequencies. The two mass- and redshift-dependent calibrations sit
below the fixed-q one at 150 MHz and above it at 1.4 GHz and 10 GHz. Their
largest-to-smallest ratio across the three total-q blocks (``bell2003``,
``delvecchio2021``, ``mccheyne2022``) is 29 % at 150 MHz, 17 % at 1.4 GHz and 49 % at
10 GHz, so the spread is largest at the high-frequency end.

(Right) The AGN blocks, on a radio-loud AGN (``loudness`` = 2) with ``bell2003``
star formation. ``dpl`` bends: it is a broken double power law with an
exponential synchrotron-aging cutoff. ``powerlaw`` keeps one slope. The two
cross near 5 GHz, where their ratio is 1.00. Below that ``dpl`` is lower (0.16
at 150 MHz, 0.55 at 1.4 GHz) and above it higher (1.30 at 10 GHz, 1.81 at
100 GHz). The AGN block therefore changes the spectral shape, not only the
normalization.
``none`` is star-forming synchrotron alone.

``loudness`` is ``log10(L_5GHz / L_B)``, so 0 is the radio-quiet boundary and
the 2.0 used here is a radio-loud source; its prior runs to 4. Passing 100
"to be safe" is not off the end of a scale, it is 1e100.

Reference: Bell+2003; Delvecchio+2021; McCheyne+2022 (q_IR calibrations).
"""

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
from tengri.units import C_AA

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

SFH = {"type": "const", "all_params": tengri.Fixed(tengri.DEFAULT), "log_total_mass": 10.5}
DUST = {
    "law": "power_law",
    "type": "two_component",
    "all_params": tengri.Fixed(tengri.DEFAULT),
    "tau_diff": 1.0,
    "tau_bc": 1.5,
}
# dale2014_cigale: this example enables the radio component, and plain
# dale2014 embeds its own SF radio continuum — the pair is refused at
# build as a double-count.
DUST_EMISSION = {"type": "dale2014_cigale", "all_params": tengri.Fixed(tengri.DEFAULT)}
AGN = {
    "type": "composable",
    "all_params": tengri.Fixed(tengri.DEFAULT),
    "disc": {"type": "qsogen", "all_params": tengri.Fixed(tengri.DEFAULT)},
    "torus": {"type": "skirtor", "all_params": tengri.Fixed(tengri.DEFAULT)},
    "log_lbol": 12.0,  # log10(L_bol / L_sun) at API level, never erg/s
}

ssp = tengri.load_ssp("fsps_prsc_miles_chabrier", download=True)


def spectrum(radio, *, with_agn):
    """L_nu on a frequency axis for one radio configuration."""
    model = tengri.SEDModel.build(
        ssp_data=ssp,
        sfh=SFH,
        dust_attenuation=DUST,
        dust_emission=DUST_EMISSION,
        radio=radio,
        redshift=tengri.Fixed(0.05),
        **({"agn": AGN} if with_agn else {}),
    )
    # Nothing free, so the draw is the declared values: same galaxy each time.
    assert not model.spec.free_params, model.spec.free_params
    pred = model.predict(model.spec.sample(jax.random.PRNGKey(0)))
    nu_ghz = (C_AA / np.asarray(pred.wave_rest)) / 1e9
    return nu_ghz, np.asarray(pred.rest_sed())


fig, (ax_sf, ax_agn) = plt.subplots(1, 2, figsize=(11.0, 4.2), sharey=True)

sf_blocks = [r["name"] for r in tengri.list_radio_blocks() if r["category"] == "sf"]
sf_blocks = [b for b in sf_blocks if b != "none"]
for name, color in zip(sf_blocks, plt.get_cmap("viridis")(np.linspace(0.1, 0.85, len(sf_blocks)))):
    nu, sed = spectrum(
        {
            "sf": {"type": name, "all_params": tengri.Fixed(tengri.DEFAULT)},
            "agn": {"type": "none"},
            "all_params": tengri.Fixed(tengri.DEFAULT),
        },
        with_agn=False,
    )
    band = (nu > 0.05) & (nu < 100.0)
    ax_sf.loglog(nu[band], sed[band], color=color, lw=1.4, label=name)

agn_blocks = [r["name"] for r in tengri.list_radio_blocks() if r["category"] == "agn"]
for name, color in zip(
    agn_blocks, plt.get_cmap("viridis")(np.linspace(0.1, 0.85, len(agn_blocks)))
):
    nu, sed = spectrum(
        {
            "sf": {"type": "bell2003", "all_params": tengri.Fixed(tengri.DEFAULT)},
            "agn": {"type": name, "all_params": tengri.Fixed(tengri.DEFAULT), "loudness": 2.0},
            "all_params": tengri.Fixed(tengri.DEFAULT),
        },
        with_agn=True,
    )
    band = (nu > 0.05) & (nu < 100.0)
    ax_agn.loglog(nu[band], sed[band], color=color, lw=1.4, label=name)

for ax, label in ((ax_sf, "star-forming block"), (ax_agn, "AGN block")):
    ax.axvline(0.15, color="0.8", lw=0.4, ls=":")
    ax.axvline(1.4, color="0.8", lw=0.4, ls=":")
    ax.set_xlabel(r"Rest-frame frequency $\nu$ [GHz]")
    ax.legend(frameon=False, fontsize=8, title=label, title_fontsize=8)
ax_sf.set_ylabel(r"$L_\nu$ [erg s$^{-1}$ Hz$^{-1}$]")

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