import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Patch
import matplotlib.cm as cm
from matplotlib.lines import Line2D

# ==================================
# Global styling
# ==================================
mpl.rcParams.update({
    "font.family": "serif",
    "mathtext.fontset": "cm",
    "font.size": 15,

    "axes.labelsize": 18,
    "axes.titlesize": 18,

    "xtick.labelsize": 14,
    "ytick.labelsize": 14,

    "legend.fontsize": 13,

    "axes.linewidth": 1.2,

    "xtick.direction": "in",
    "ytick.direction": "in",

    "xtick.top": True,
    "ytick.right": True,
})

# ==================================
# Dataset list
# ==================================
datasets = ["GW240515", "GW241113", "GW241225_08"]
legend_names = ["GW240515", "GW241113", "GW241225_08"]

# ==================================
# Colormap
# ==================================
cmap = cm.get_cmap("tab10", len(datasets))
colors = [cmap(i) for i in range(len(datasets))]

# ==================================
# Create figure
# ==================================
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 9), sharex=True)

legend_scalar = []
legend_vector = []

# ==================================
# Loop over datasets
# ==================================
for dataset, color, legend_name in zip(datasets, colors, legend_names):

    scalar = np.load(
        f"scalar_data_{dataset}.npz"
    )

    vector = np.load(
        f"vector_data_{dataset}.npz"
    )

    # ---------------------------------
    # Scalar
    # ---------------------------------
    ax1.contourf(
        scalar['MU_s1'],
        scalar['TAGE_s1'],
        scalar['ratio_s1'],
        levels=[0, 0.1],
        colors=[color],
        alpha=0.25
    )

    ax1.contour(
        scalar['MU_s1'],
        scalar['TAGE_s1'],
        scalar['ratio_s1'],
        levels=[0.1],
        colors=[color],
        linewidths=2
    )

    # ---------------------------------
    # Vector
    # ---------------------------------
    ax2.contourf(
        vector['MU_v1'],
        vector['TAGE_v1'],
        vector['ratio_v1'],
        levels=[0, 0.1],
        colors=[color],
        alpha=0.25
    )

    ax2.contour(
        vector['MU_v1'],
        vector['TAGE_v1'],
        vector['ratio_v1'],
        levels=[0.1],
        colors=[color],
        linewidths=2
    )

    # ---------------------------------
    # Legends (datasets)
    # ---------------------------------
    legend_scalar.append(
        Patch(facecolor=color, edgecolor='none', alpha=0.25, label=legend_name)
    )

    legend_vector.append(
        Patch(facecolor=color, edgecolor='none', alpha=0.25, label=legend_name)
    )

# ==================================
# Axis scaling
# ==================================
ax1.set_xscale('log')
ax1.set_yscale('log')

ax2.set_xscale('log')
ax2.set_yscale('log')

# ==================================
# Limits
# ==================================
ax2.set_xlim(1e-15, 1e-11)
ax2.set_ylim(1e5, 1e7)

# ==================================
# Labels
# ==================================
ax1.set_ylabel(r"Black hole age [yr]")
ax2.set_xlabel(r"$m_b \,[\mathrm{eV}]$")
ax2.set_ylabel(r"Black hole age [yr]")

# ==================================
# Grid + minor ticks
# ==================================
for ax in [ax1, ax2]:
    ax.grid(True, which="major", alpha=0.4)
    ax.minorticks_on()

# ==================================
# Subplot labels
# ==================================
ax1.text(
    0.03, 0.07, "Scalar",
    transform=ax1.transAxes,
    fontsize=16,
    ha='left',
    bbox=dict(boxstyle='round,pad=0.3', fc='white', ec='none', alpha=0.8)
)

ax2.text(
    0.03, 0.07, "Vector",
    transform=ax2.transAxes,
    fontsize=16,
    ha='left',
    bbox=dict(boxstyle='round,pad=0.3', fc='white', ec='none', alpha=0.8)
)

# ==================================
# Existing constraints
# ==================================
scalar_excl = (0.55e-13, 26e-13)
vector_excl = (0.11e-13, 53e-13)

# ----------------------------------
# Draw exclusion lines
# ----------------------------------
ax1.plot(
    scalar_excl,
    [0, 0],
    transform=ax1.get_xaxis_transform(),
    color='red',
    linewidth=10,
    zorder=0,
    solid_capstyle='butt'
)

ax2.plot(
    vector_excl,
    [0, 0],
    transform=ax2.get_xaxis_transform(),
    color='red',
    linewidth=10,
    zorder=0,
    solid_capstyle='butt'
)

# ==================================
# Legend handle for exclusion line
# ==================================
exclusion_handle = Line2D(
    [0], [0],
    color='red',
    linewidth=4,
    label=r"Existing constraints ($10^5$ yr)"
)

# ==================================
# Legends
# ==================================
ax1.legend(handles=legend_scalar + [exclusion_handle], loc='upper left', frameon=False)
ax2.legend(handles=legend_vector + [exclusion_handle], loc='upper left', frameon=False)

# ==================================
# Final layout + save
# ==================================
plt.tight_layout()

plt.savefig(
    "final_plot_all.pdf",
    dpi=300,
    bbox_inches='tight'
)

plt.show()