import marimo

__generated_with = "0.10.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    return (mo,)


@app.cell
def _(mo):
    mo.md(
        """
        # ADAM — Tropical Storms example

        Pick an alert level and a date window — the forecast track nodes are
        fetched live.
        """
    )
    return


@app.cell
def _(mo):
    alert = mo.ui.dropdown(
        options=["Red", "Orange", "Green", "any"], value="Red", label="Alert level"
    )
    days = mo.ui.slider(7, 180, value=30, label="Window (last N days)")
    mo.hstack([alert, days])
    return alert, days


@app.cell
async def _(alert, days):
    import urllib.parse
    from datetime import datetime, timedelta, timezone

    BASE = "https://api.adam.geospatial.wfp.org/api"
    since = (datetime.now(timezone.utc) - timedelta(days=days.value)).strftime(
        "%Y-%m-%dT%H:%M:%S"
    )
    filter_parts = [f"published_at > TIMESTAMP('{since}')"]
    if alert.value != "any":
        filter_parts.append(f"alert_level = '{alert.value}'")
    params = urllib.parse.urlencode(
        {
            "filter": " AND ".join(filter_parts),
            "sortby": "-wind_speed",
            "limit": 50,
        }
    )
    url = f"{BASE}/collections/adam.adam_ts_events/items?{params}"

    try:
        from pyodide.http import pyfetch

        resp = await pyfetch(url, headers={"Accept": "application/geo+json"})
        data = await resp.json()
    except ImportError:
        import json
        import urllib.request

        req = urllib.request.Request(
            url, headers={"Accept": "application/geo+json"}
        )
        with urllib.request.urlopen(req) as r:
            data = json.loads(r.read())
    return (data,)


@app.cell
def _(data):
    import pandas as pd

    df = pd.DataFrame([f["properties"] for f in data["features"]])
    cols = [
        "name",
        "published_at",
        "current_storm_status",
        "alert_level",
        "wind_speed",
        "max_storm_surge",
        "iso3",
        "cleared",
    ]
    df_view = df[[c for c in cols if c in df.columns]]
    df_view
    return (df,)


@app.cell
def _(df):
    import matplotlib.pyplot as plt

    if "wind_speed" in df and len(df):
        fig, ax = plt.subplots(figsize=(7, 3))
        df.sort_values("wind_speed", ascending=True).plot.barh(
            x="name", y="wind_speed", ax=ax, color="#00838f", legend=False
        )
        ax.set_xlabel("Peak wind (km/h)")
        ax.set_ylabel("Storm")
        ax.set_title(f"{len(df)} storms — peak wind ranking")
        fig
    return


if __name__ == "__main__":
    app.run()
