# %% [markdown]
# # How does a parcel ascend through a warm conveyor belt?
#
# A warm conveyor belt carries moist air from the lower troposphere into
# the outflow of an extratropical cyclone. Follow one simulated air parcel
# from the ICON ensemble of Oertel et al. (2025). Use its recorded altitude,
# pressure, temperature and water species as a one-dimensional parcel trace.
# The clock runs from ten hours before the onset of ascent to 58 hours after.
# [Dataset and attribution](https://doi.org/10.35097/ecgs4f56mp3ymjmt)
# · [Ascent definition](https://doi.org/10.1002/qj.4986)
#
# The first member is ID000. Trajectory index 0 lacks two timestamps,
# so zero-based index 1 is the first complete qualifying track.
# The trajectory and derived plot are adapted under the original
# [CC BY-NC-SA 4.0 license](https://creativecommons.org/licenses/by-nc-sa/4.0/).
#
# The archived pressure is in hPa and the humidity is a mass fraction of
# the ICON air mixture. The archive supplies vapor, cloud water, rain, ice,
# snow and graupel. The model also prognoses hail, but the trajectory file
# omits its mass fraction. Set unarchived hail to zero for the conversion.
# If hail was present, this assumption overestimates dry mass and gives a
# lower bound on vapor per kilogram of dry air.
# For a parcel containing 1 kg dry air, the ideal-gas volume in cubic
# metres is $(R_d+r_v R_v)T/p$, where $r_v=q_v/q_d$.
# [ICON constituent mass fractions, section 3.1](https://www.cosmo-model.org/content/model/documentation/core/iconTutorial_dwd_2023.pdf)

# %%
import hashlib
import json
from pathlib import Path
from tempfile import TemporaryDirectory

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 RD, RV, ParcelInitialState
from particula.dynamics.parcel_replay import ParcelTrace, replay

SOURCE_DIR = Path("docs/data/wcb-trajectory")
WATER = ("qv", "qc", "qr", "qi", "qs", "qg")


# %% [markdown]
# ## Translate the source records into parcel forcing
#
# Preserve the archived coordinates in time and height. One zero-count
# aerosol class fills the trace's initial population slot. It contributes
# zero particle mass at every step, so the replay can follow the forcing
# through mixed-phase and icy air without inferring droplet growth there.
# Identify the source by ensemble member, zero-based trajectory index and
# the digest of the original NetCDF member.


# %%
def make_trace(rows, metadata):
    """Convert 69 hourly KIT records to SI forcing for 1 kg dry air."""
    hours, height, pressure, temperature = (
        rows[key] for key in ("time", "alt", "p", "t")
    )
    dry_fraction = 1.0 - sum(rows[key] for key in WATER)
    vapor = rows["qv"] / dry_fraction
    pressure = pressure * 100
    dry_radius = np.array([100e-9])
    initial = ParcelInitialState(
        dry_radius=dry_radius,
        number=np.array([0.0]),
        kappa=0.5,
        pressure=pressure[0],
        temperature=temperature[0],
        vapor=vapor[0],
        height=height[0],
        dry_air_mass=1.0,
    )
    return ParcelTrace(
        parcel_id=f"{metadata['member']}-ntra-{metadata['ntra_zero_based']}",
        provenance=(
            f"doi:{metadata['doi']} member SHA-256 {metadata['member_sha256']}; "
            f"{metadata['replay_humidity_assumption']}"
        ),
        time=hours * 3600,
        height=height,
        pressure=pressure,
        temperature=temperature,
        volume=(RD + vapor * RV) * temperature / pressure,
        vapor=vapor,
        initial=initial,
        initial_wet=dry_radius,
    )


# %% [markdown]
# ## Replay the hourly states
#
# Save and reopen the trace with the Particula reader, then advance its
# prescribed parcel history. Compare the original source fields at all
# 69 timestamps and convert the replay humidity back to the ICON basis
# using $q_v=r_v(1-\sum q_{cond})/(1+r_v)$. This inverse uses the
# archived condensate fractions independently at each hour. The hourly
# spacing supports synoptic ascent times and integrated displacements.


# %%
def run_example(source_dir=SOURCE_DIR):
    """Check all archived forcing records and replay their volume history."""
    source_dir = Path(source_dir)
    table = source_dir / "source.csv"
    meta = json.loads((source_dir / "source.json").read_text())
    if (
        hashlib.sha256(table.read_bytes()).hexdigest()
        != meta["source_csv_sha256"]
    ):
        raise ValueError(
            "Trajectory source checksum differs from its provenance"
        )
    rows = np.genfromtxt(table, names=True, delimiter=",")
    trace = make_trace(rows, meta)
    with TemporaryDirectory() as tmp:
        path = Path(tmp) / "forcing.csv"
        trace.save(path)
        restored = ParcelTrace.load(path)
    np.testing.assert_array_equal(restored.time / 3600, rows["time"])
    np.testing.assert_array_equal(restored.height, rows["alt"])
    np.testing.assert_array_equal(restored.pressure / 100, rows["p"])
    np.testing.assert_array_equal(restored.temperature, rows["t"])
    result = replay(restored, max_step=3600, device="cpu")
    np.testing.assert_array_equal(result.time, restored.time)
    np.testing.assert_allclose(result.volume, restored.volume, rtol=1e-13)
    water_kg = result.gas_masses[:, result.gas_species.index("water")]
    vapor = water_kg / restored.initial.dry_air_mass
    condensate = sum(rows[key] for key in WATER[1:])
    recovered = vapor * (1 - condensate) / (1 + vapor)
    np.testing.assert_allclose(recovered, rows["qv"], rtol=5e-15, atol=0)
    np.testing.assert_array_equal(result.number, np.zeros_like(result.number))
    return {
        "time_h": rows["time"].tolist(),
        "height_km": (rows["alt"] / 1000).tolist(),
        "pressure_hpa": rows["p"].tolist(),
        "temperature_k": rows["t"].tolist(),
        "vapor_g_kg_dry": (1000 * vapor).tolist(),
        "volume_m3": result.volume.tolist(),
        "specific_humidity_residual": (recovered - rows["qv"]).tolist(),
        "trajectory": trace.parcel_id,
        "doi": meta["doi"],
        "member_sha256": meta["member_sha256"],
        "humidity_assumption": meta["replay_humidity_assumption"],
    }


# %% [markdown]
# ## Read the ascent and outflow
#
# The zero-hour line marks the source-defined start of ascent. Compare
# the rise in altitude with the pressure drop and cooling. The dry-air
# vapor mixing ratio also responds to phase changes and mixing represented
# in the driving ICON simulation. This single path samples both inflow
# and outflow and cannot establish the frequency of cloud types.


# %%
@mplstyle.context("particula.default")
def plot_results(report):
    """Plot source altitude, pressure, temperature and dry-basis vapor."""
    fig, axes = plt.subplots(
        2, 2, figsize=(8, 5), sharex=True, layout="constrained"
    )
    panels = (
        ("height_km", "Altitude (km)"),
        ("pressure_hpa", "Pressure (hPa)"),
        ("temperature_k", "Temperature (K)"),
        ("vapor_g_kg_dry", "Vapor (g/kg dry air)"),
    )
    for ax, (name, units) in zip(axes.flat, panels, strict=True):
        ax.plot(report["time_h"], report[name], color="#236c8b")
        ax.axvline(0, color="0.45", ls=":", lw=1)
        ax.set_ylabel(units)
    for ax in axes[-1]:
        ax.set_xlabel("Hours from ascent onset")
    return fig


if __name__ == "__main__":
    plot_results(run_example())
    plt.show()

# %% [markdown]
# Within three hours of ascent onset the parcel drops 614 hPa in pressure
# and cools from 291.2 to 240.6 K. By hour 58 it reaches 11.63 km with
# 0.0258 g vapor/kg dry air. Restoring the archived humidity basis recovers
# every value to within 1.8 × 10⁻¹⁸ kg/kg under the same hail assumption.
# This round trip checks conversion arithmetic. The trajectory includes regions
# cold enough for ice. The replay uses the archived vapor and condensates
# to move between humidity conventions while prescribing the thermal history.
