# %% [markdown]
# # How long can a ridge crossing lift a parcel above water saturation?
#
# An air parcel passing over a gentle ridge cools as it rises. Over wide
# ridges a stationary wave can propagate upward. Over narrow ridges the
# disturbance can decay before it reaches the parcel. Compare two sinusoidal
# ridges of equal amplitude (60 m) under a 10 m/s wind with a uniform
# buoyancy frequency of 0.01/s. A flat-terrain control follows the same air.
# The wind uses the [linear mountain-wave solution](../../../../theory/dynamics/linear-mountain-waves.md).
#
# ## Follow a streamline and count time above saturation
#
# Start 1 km above the linearized lower boundary at the wave's trough. A
# height-triggered event marks each crossing of water saturation. Stop after
# one terrain wavelength of eastward travel. The parcel conserves vapor and
# cools along a dry adiabatic path with water-vapor loading. This calculation
# estimates potential saturation exposure before accounting for condensation,
# latent heat or depletion of the vapor.

# %%
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style as mplstyle
from particula import plotting  # noqa: F401
from particula.dynamics.parcel import CP, LATENT, RD, RV
from particula.flow.kinematic.mountain_wave import MountainWave
from particula.util.constants import STANDARD_GRAVITY
from scipy.integrate import solve_ivp


def saturation_pressure(temperature):
    """Liquid saturation vapor pressure (Pa) with constant latent heat."""
    return 611.2 * np.exp(LATENT / RV * (1 / 273.15 - 1 / temperature))


def cross_ridge(wave):
    """Sample a parcel across one wavelength starting at the wave trough."""
    z0, t0, p0, rh0 = 1000.0, 284.0, 90000.0, 0.97
    e0 = rh0 * saturation_pressure(t0)
    vapor = RD / RV * e0 / (p0 - e0)
    k = 2 * np.pi / wave.wavelength
    m = np.sqrt(max(0, wave.vertical_wavenumber_squared))
    x0 = (np.pi - m * z0) / k

    def thermal_state(height):
        temp = t0 - (1 + vapor) * STANDARD_GRAVITY / CP * (height - z0)
        pressure = p0 * (temp / t0) ** (CP / (RD + vapor * RV))
        humidity = e0 * pressure / p0 / saturation_pressure(temp)
        return temp, humidity

    def wind(t, xyz):
        return wave.velocity(xyz[None, :], t)[0]

    def transit(_, xyz):
        return xyz[0] - x0 - wave.wavelength

    transit.terminal = True

    def saturation(_, xyz):
        return thermal_state(xyz[2])[1] - 1

    advective_time = wave.wavelength / wave.wind_speed
    path = solve_ivp(
        wind,
        (0, 2 * advective_time),
        [x0, 0, z0],
        events=(transit, saturation),
        dense_output=True,
        method="DOP853",
        rtol=1e-10,
        atol=1e-9,
        max_step=advective_time / 60,
    )
    if not path.success or not path.t_events[0].size:
        raise RuntimeError("Parcel failed to reach the end of the ridge.")
    end = path.t_events[0][0]
    crossings = np.r_[0, path.t_events[1], end]
    midpoints = (crossings[:-1] + crossings[1:]) / 2
    saturated = thermal_state(path.sol(midpoints)[2])[1] > 1
    times = np.linspace(0, end, 121)
    position = path.sol(times)
    temp, humidity = thermal_state(position[2])
    return {
        "time_s": times.tolist(),
        "distance_m": (position[0] - x0).tolist(),
        "height_m": position[2].tolist(),
        "temperature_k": temp.tolist(),
        "relative_humidity": humidity.tolist(),
        "saturation_crossings_s": path.t_events[1].tolist(),
        "exposure_s": float(np.diff(crossings)[saturated].sum()),
        "wavelength_m": wave.wavelength,
    }


# %% [markdown]
# ## Compare the same parcel over three ridges
#
# At the chosen wind and stability, 12 km and 3 km fall on opposite sides
# of the propagation cutoff. Normalize the horizontal distance by the ridge
# wavelength to line up the wind cycles. Use elapsed time for humidity and
# temperature so that the length of the saturated interval remains visible.


# %%
def simulate():
    """Return parcel crossings for propagating, evanescent and flat controls."""
    cases = {
        "Wide ridge": (12000, 60),
        "Narrow ridge": (3000, 60),
        "Flat": (12000, 0),
    }
    return {
        name: cross_ridge(MountainWave(10, 0.01, width, amplitude))
        for name, (width, amplitude) in cases.items()
    }


@mplstyle.context("particula.default")
def plot_results(report):
    """Plot lift, cooling and potential water saturation in each crossing."""
    fig, axes = plt.subplots(1, 3, figsize=(11, 3.8), layout="constrained")
    for name, case in report.items():
        t = np.asarray(case["time_s"]) / 60
        distance = np.asarray(case["distance_m"]) / case["wavelength_m"]
        axes[0].plot(distance, case["height_m"], label=name)
        axes[1].plot(t, case["temperature_k"])
        axes[2].plot(t, 100 * np.asarray(case["relative_humidity"]))
    axes[0].set(xlabel="Distance / wavelength", ylabel="Height (m)")
    axes[1].set(xlabel="Elapsed time (min)", ylabel="Temperature (K)")
    axes[2].set(xlabel="Elapsed time (min)", ylabel="Relative humidity (%)")
    axes[2].axhline(100, ls=":", color="0.4")
    axes[0].legend()
    return fig


def run_example():
    """Print cooling and potential saturation exposure and display the paths."""
    report = simulate()
    for name, case in report.items():
        print(
            f"{name}: {284 - min(case['temperature_k']):.2f} K cooling, "
            f"{case['exposure_s']:.1f} s above water saturation"
        )
    plot_results(report)
    plt.show()
    return report


if __name__ == "__main__":
    run_example()

# %% [markdown]
# The wide ridge cools the air by 1.18 K and gives about 625 s above
# saturation. The narrow ridge at this release height cools the air by just
# 0.18 K and stays below saturation, as does the flat control. A wave that decays rapidly in the vertical can still lift air
# near the surface. Repeat the narrow-ridge run with a lower initial parcel
# to test how strongly the saturation interval depends on the release height.
