# %% [markdown]
# # Can the timing of ascent change cloud activation at the same final height?
#
# Lift two closed parcels through the same distance in ten minutes. Both
# start with the same aerosol and humidity. One parcel follows the
# [KiD-A warm-column pulse](https://github.com/Adehill/KiD-A/blob/dcaf19a592942e7858c6f47fdba3591590e2c532/src/test_cases.f90)
# sampled every 20 s. Its speed rises from zero to 2 m/s and falls again.
# The other parcel rises steadily at the pulse's mean speed. Only the wind
# history comes from KiD-A. Follow supersaturation and count the droplets
# that grow beyond their critical wet radius.
#
# ## Count activated particles
#
# The peak of each class's κ-Köhler curve gives its critical wet radius at
# the parcel temperature. Solve for zero slope in the logarithm of the
# equilibrium saturation ratio. Weight each class by its number of particles.
# A class may deactivate as the parcel approaches the end of the pulse.

# %%
from dataclasses import replace

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 (
    RHO_W,
    RV,
    SIGMA,
    ParcelInitialState,
    run_parcel,
)
from particula.flow.kinematic.parcel_wind import CirrusWave, TabulatedUpdraft
from scipy.optimize import brentq


def activated_fraction(parcel):
    """Return the fraction of represented particles above their Köhler peak."""
    initial = parcel.initial
    kelvin = 2 * SIGMA / (RV * RHO_W * parcel.temperature)
    critical = np.empty_like(parcel.wet_radius)
    for j, dry in enumerate(initial.dry_radius):
        for i, length in enumerate(kelvin):

            def slope(ratio, length=length, dry=dry):
                return 3 * initial.kappa * ratio**4 - length / dry * (
                    ratio**3 - 1
                ) * (ratio**3 - 1 + initial.kappa)

            critical[i, j] = dry * brentq(slope, 1, 1000)
    return np.average(
        parcel.wet_radius > critical, weights=initial.number, axis=1
    )


# %% [markdown]
# ## Compare the pulse and the constant control
#
# Give each parcel one kilogram of dry air and the same three soluble aerosol
# classes. The pressure work and the parcel height use the same prescribed
# velocity. Vapor and liquid may exchange mass, so check their sum throughout
# each run. A separate dry parcel follows the
# [sinusoidal cirrus experiment](https://journals.ametsoc.org/view/journals/atsc/55/11/1520-0469_1998_055_1940_dioccf_2.0.co_2.xml)
# for two periods. Its exact displacement tests both ascent and descent.
# The cirrus comparison uses prescribed motion only and omits ice processes.


# %%
def simulate():
    """Return warm-parcel activation histories and a dry wave control."""
    initial = ParcelInitialState(
        dry_radius=np.array([20, 35, 80]) * 1e-9,
        number=np.array([3e7, 4e7, 3e7]),
        kappa=0.5,
        pressure=90000.0,
        temperature=288.15,
        vapor=0.0118,
    )
    times = np.linspace(0, 600, 31)
    pulse = TabulatedUpdraft(times, 2 * np.sin(np.pi * times / 600))
    steady = float(pulse.displacement(600) / 600)
    cases = {}
    for name, wind in (("Pulse", pulse), ("Constant", steady)):
        parcel = run_parcel(initial, updraft=wind, steps=300, timestep=2)
        water = parcel.vapor + parcel.liquid
        cases[name] = {
            "height_m": parcel.height.tolist(),
            "supersaturation_pct": (100 * parcel.supersaturation).tolist(),
            "activated_fraction": activated_fraction(parcel).tolist(),
            "water_drift_kg_kg": float(np.max(np.abs(water - water[0]))),
        }
    dry = replace(
        initial, vapor=0, height=9500, temperature=230, pressure=26000
    )
    wave = CirrusWave()
    control = run_parcel(
        dry, updraft=wave, steps=120, timestep=10, phase_exchange=False
    )
    exact = 0.3 * 600 / (2 * np.pi) * np.sin(2 * np.pi * control.time / 600)
    return {
        "time_s": parcel.time.tolist(),
        "pulse_m_s": pulse.velocity(parcel.time).tolist(),
        "constant_m_s": steady,
        "cases": cases,
        "wave_time_s": control.time.tolist(),
        "wave_displacement_m": (control.height - dry.height).tolist(),
        "wave_temperature_k": control.temperature.tolist(),
        "wave_height_error_m": float(
            np.max(abs(control.height - dry.height - exact))
        ),
    }


# %% [markdown]
# ## Read the activation history
#
# Match the line colors across the warm-parcel panels to compare speed,
# supersaturation over liquid water, and the fraction of particles activated.
# In the dry control, a complete wave should return the parcel to its
# starting altitude even though it has experienced two temperature extrema.


# %%
@mplstyle.context("particula.default")
def plot_results(report):
    """Plot prescribed wind, droplet activation and the cirrus displacement."""
    fig, axes = plt.subplots(2, 2, figsize=(9, 6), layout="constrained")
    t = np.asarray(report["time_s"]) / 60
    axes[0, 0].plot(t, report["pulse_m_s"], label="Pulse")
    axes[0, 0].plot(
        t, np.full_like(t, report["constant_m_s"]), label="Constant"
    )
    axes[0, 0].set_ylabel("Updraft (m/s)")
    axes[0, 0].legend()
    for name, case in report["cases"].items():
        axes[0, 1].plot(t, case["supersaturation_pct"], label=name)
        axes[1, 0].step(t, case["activated_fraction"], where="post", label=name)
    axes[0, 1].axhline(0, color="0.6", lw=0.8)
    axes[0, 1].set_ylabel("Supersaturation (%)")
    axes[1, 0].set_ylabel("Activated number fraction")
    axes[1, 0].set_ylim(-0.05, 1.05)
    axes[1, 1].plot(
        np.array(report["wave_time_s"]) / 60, report["wave_displacement_m"]
    )
    axes[1, 1].set_ylabel("Dry cirrus displacement (m)")
    for ax in axes.flat:
        ax.set_xlabel("Elapsed time (min)")
    return fig


def run_example():
    """Run the two cloud-forcing comparisons and display the four panels."""
    report = simulate()
    for name, case in report["cases"].items():
        print(
            f"{name}: peak supersaturation {max(case['supersaturation_pct']):.3f}%, "
            f"water drift {case['water_drift_kg_kg']:.2e} kg/kg dry air"
        )
    plot_results(report)
    plt.show()
    return report


if __name__ == "__main__":
    run_example()

# %% [markdown]
# Both parcels rise 763 m. At our 2 s sampling interval, the first class
# exceeds its critical radius at 98 s under pulsed lift and at 40 s under
# steady lift. The pulse peaks at 0.666% supersaturation and activates 70%
# of the count. Steady lift peaks at 0.715% and activates all three classes.
# Supersaturation and droplet growth depend on *when* the parcel cools
# relative to its available droplet surface. The separate wave tests
# displacement during reversals. For a more polluted parcel, increase the represented counts in
# both warm runs and compare when each size class crosses its Köhler peak.
