import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

from matplotlib.ticker import ScalarFormatter
from scipy.interpolate import interp1d


# ==================================
# 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": False,
    "ytick.right": True,
})


# ==================================
# Crossing function
# ==================================

def find_crossings(x, y, level=0.9):

    crossings = []

    for i in range(len(x)-1):

        if (y[i]-level)*(y[i+1]-level) < 0:

            x0, x1 = x[i], x[i+1]
            y0, y1 = y[i], y[i+1]

            x_cross = x0 + (level-y0)*(x1-x0)/(y1-y0)

            crossings.append(x_cross)

    return sorted(crossings)



# ==================================
# Optimal boson masses
# ==================================

GW250114_mV_opt = 3.554494e-13
GW250207_mV_opt = 3.628378e-13



# ==================================
# Load data product
# ==================================

filename = "GW250114_GW250207_detection_probability.txt"


data = np.genfromtxt(
    filename,
    dtype=None,
    names=True,
    encoding=None
)



# ==================================
# Separate events
# ==================================

GW250114 = data[data["event"] == "GW250114"]

GW250207 = data[data["event"] == "GW250207"]



# ==================================
# Extract quantities
# ==================================

mV_1 = GW250114["boson_mass_eV"]
R1_1FAR = GW250114["Pdet"]
err1_1FAR = GW250114["uncertainty"]
f1 = GW250114["frequency_Hz"]


mV_2_all = GW250207["boson_mass_eV"]
R2_1FAR_all = GW250207["Pdet"]
err2_1FAR_all = GW250207["uncertainty"]
f2_all = GW250207["frequency_Hz"]



# ==================================
# Frequency mapping
# ==================================

mV_common = 0.5*(mV_1 + mV_2_all[:len(mV_1)])

f_common = 0.5*(f1 + f2_all[:len(f1)])


m_to_f = interp1d(
    mV_common,
    f_common,
    kind="linear",
    fill_value="extrapolate"
)


f_to_m = interp1d(
    f_common,
    mV_common,
    kind="linear",
    fill_value="extrapolate"
)



# ==================================
# Plot
# ==================================

fig, ax = plt.subplots(
    figsize=(8,5.5)
)



# ---------------------------------
# GW250114
# ---------------------------------

ax.errorbar(
    mV_1,
    R1_1FAR,
    yerr=err1_1FAR,
    fmt="o",
    markersize=6,
    capsize=4,
    capthick=1.3,
    elinewidth=1.3,
    color="tab:blue",
    label=r"GW250114 ($P_{\rm fa}=1\%$)"
)


ax.plot(
    mV_1,
    R1_1FAR,
    "-",
    color="tab:blue",
    linewidth=2
)



cross1 = find_crossings(
    mV_1,
    R1_1FAR
)


print("\nGW250114 crossings:")
print(cross1)


if len(cross1) >= 2:

    ax.axvspan(
        cross1[0],
        cross1[1],
        color="tab:blue",
        alpha=0.2
    )


ax.axvline(
    GW250114_mV_opt,
    color="tab:blue",
    linestyle=":",
    linewidth=2
)



# ---------------------------------
# GW250207
# ---------------------------------

ax.errorbar(
    mV_2_all,
    R2_1FAR_all,
    yerr=err2_1FAR_all,
    fmt="o",
    markersize=6,
    capsize=4,
    capthick=1.3,
    elinewidth=1.3,
    color="tab:orange",
    label=r"GW250207 ($P_{\rm fa}=1\%$)"
)



# solid part
ax.plot(
    mV_2_all[:-1],
    R2_1FAR_all[:-1],
    "-",
    color="tab:orange",
    linewidth=2
)


# dashed extrapolated final segment
ax.plot(
    mV_2_all[-2:],
    R2_1FAR_all[-2:],
    "--",
    color="tab:orange",
    linewidth=2
)



cross2 = find_crossings(
    mV_2_all,
    R2_1FAR_all
)


print("\nGW250207 crossings:")
print(cross2)


if len(cross2) >= 2:

    ax.axvspan(
        cross2[0],
        cross2[1],
        color="tab:orange",
        alpha=0.2
    )



ax.axvline(
    GW250207_mV_opt,
    color="tab:orange",
    linestyle=":",
    linewidth=2
)



# ==================================
# Optimal mass legend
# ==================================

ax.plot(
    [],
    [],
    color="black",
    linestyle=":",
    linewidth=2,
    label=r"$m_V^{\rm opt}$"
)



# ==================================
# Axis formatting
# ==================================

ax.set_xlabel(
    r"$m_V\,[\mathrm{eV}]$"
)


ax.set_ylabel(
    r"$P_{\rm det}$"
)



formatter = ScalarFormatter(
    useMathText=True
)

formatter.set_powerlimits(
    (0,0)
)


ax.xaxis.set_major_formatter(
    formatter
)


ax.ticklabel_format(
    axis="x",
    style="sci",
    scilimits=(0,0)
)



ax.grid(
    True,
    which="major",
    alpha=0.4
)


ax.minorticks_on()



# ==================================
# Frequency axis
# ==================================

secax = ax.secondary_xaxis(
    "top",
    functions=(
        lambda m:m_to_f(m),
        lambda f:f_to_m(f)
    )
)


secax.set_xlabel(
    r"$f_0\,[\mathrm{Hz}]$"
)


secax.tick_params(
    direction="in"
)


secax.minorticks_on()



# ==================================
# Legend
# ==================================

ax.legend(
    loc="center",
    bbox_to_anchor=(3.7e-13,0.4),
    bbox_transform=ax.transData
)



plt.tight_layout()



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



plt.show()