"""Compare intrinsic and scattered Fe XXV maps and annular spectra. [AI-Codex]"""

import argparse
from pathlib import Path

import h5py
import matplotlib.pyplot as plt
from matplotlib import patheffects
from matplotlib.colors import LogNorm
from matplotlib.patches import Circle
import numpy as np
import thorplot as tp


def load_output(directory):
    """Read physical maps and cumulative aperture spectra. [AI-Codex]"""
    products = {}
    for stream, quantity in [("input", "dlambda"), ("peel", "dlambda_peel_shifted")]:
        with h5py.File(directory / stream / "data.h5") as handle:
            if not handle.attrs.get("completed", False):
                raise ValueError(f"{stream}: simulation output is incomplete")
            image = handle["sbmap/image"]
            attrs = dict(image.attrs)
            if attrs.get("units") != "erg/s/cm2/arcsec2":
                raise ValueError("Physical surface-brightness output requires a newer THOR build.")
            spectrum = handle[f"aperturespectrum/{quantity}"]
            data, cumulative = image[:].T, spectrum[:]
            for array in (data, cumulative):
                if not np.isfinite(array).all() or np.any(array < 0):
                    raise ValueError(f"{stream}: output contains invalid values")
            products[stream] = (data, cumulative, attrs, dict(spectrum.attrs))
    return products


def main():
    """Plot the native energy surface brightness and annular line luminosity. [AI-Codex]"""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("output", nargs="?", type=Path, default=Path("output-fexxv-w"))
    parser.add_argument("--dark", action="store_true")
    args = parser.parse_args()
    products = load_output(args.output)
    attrs, spectral_attrs = products["peel"][2:]
    box_kpc = attrs["length_unit_cm"] / 3.0856775814913673e21
    extent = [(attrs[key] - 0.5) * box_kpc
              for key in ("left_x", "right_x", "left_y", "right_y")]
    radii = spectral_attrs["aperture_radii"] * box_kpc
    # The final aperture is the whole-domain reference, not a plotted annulus.
    n_annuli = len(radii) - 1
    wavelength = 1.8504  # Fe XXV w rest wavelength in THOR, Angstrom.
    edges = np.linspace(spectral_attrs["left"], spectral_attrs["right"],
                        spectral_attrs["nbins"] + 1)
    energy = (12398.419843320026 / (wavelength + edges))[::-1]
    energy_offset = energy - 12398.419843320026 / wavelength
    positive = np.concatenate([value[0][value[0] > 0] for value in products.values()])
    if not positive.size:
        raise ValueError("The maps contain no emission.")
    norm = LogNorm(vmin=np.percentile(positive, 1), vmax=positive.max())

    with tp.style(dark=args.dark):
        fig = plt.figure(figsize=(tp.DOC_FULL_WIDTH, 8.8), layout="constrained")
        grid = fig.add_gridspec(3, 2 * n_annuli, height_ratios=[5.5, 0.18, 1.4])
        maps = [fig.add_subplot(grid[0, :n_annuli]), fig.add_subplot(grid[0, n_annuli:])]
        color_axis = fig.add_subplot(grid[1, :])
        axes = [fig.add_subplot(grid[2, 2 * i:2 * i + 2]) for i in range(n_annuli)]
        colors = tp.hero_colors(["intrinsic", "thor"], dark=args.dark)
        for ax, (stream, title) in zip(maps, [("input", "Intrinsic"), ("peel", "Scattered")]):
            im = ax.imshow(products[stream][0], origin="lower", extent=extent,
                           norm=norm, cmap="magma")
            tp.imshow_panel(ax, title)
            for radius in radii[:-1]:
                ax.add_patch(Circle((0, 0), radius, fill=False, color="white", lw=0.9, alpha=0.65))
        tp.scalebar(maps[0], 100, "100 kpc")
        bar = maps[0].lines[-1]
        bar.set_solid_capstyle("projecting")
        bar.set_path_effects([
            patheffects.Stroke(linewidth=5, foreground="black", capstyle="projecting"),
            patheffects.Normal(),
        ])
        maps[0].texts[-1].set_path_effects([
            patheffects.withStroke(linewidth=2, foreground="black")
        ])
        tp.colorbar_minimal(fig, im, maps, cax=color_axis, orientation="horizontal",
                            label="Surface brightness [erg s⁻¹ cm⁻² arcsec⁻²]")
        lower = np.r_[0, radii[:-1]]
        for index, ax in enumerate(axes):
            for (stream, label, style), color in zip(
                [("input", "Intrinsic", "--"), ("peel", "Scattered", "-")], colors
            ):
                cumulative = products[stream][1]
                annulus = cumulative[index] - (cumulative[index - 1] if index else 0)
                luminosity = annulus[::-1] * products[stream][2]["luminosity_unit_erg_s"]
                ax.stairs(luminosity / np.diff(energy), energy_offset,
                          label=label, color=color, linestyle=style, lw=1.8)
            ax.set(xlabel="ΔE [eV]", xlim=(-35, 35), ylim=(0, None))
            ax.tick_params(labelsize=9)
            ax.set_xticks([-30, 0, 30])
            ax.set_title(f"{lower[index]:.0f}–{radii[index]:.0f} kpc", fontsize=12)
            tp.strip_axes(ax, left=True)
        axes[0].set_ylabel("Luminosity [erg s⁻¹ eV⁻¹]", fontsize=10)
        axes[0].legend(fontsize=8, frameon=False)
        stem = "fexxv" + ("_dark" if args.dark else "")
        tp.save_doc_figure(fig, stem, output_dir=".")
        tp.save_doc_figure(fig, stem, fmt="png", output_dir=".", dpi=160)
        plt.close(fig)


if __name__ == "__main__":
    main()
