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 — Earthquakes example

        Move the sliders and re-run: the API is queried live on every change.
        """
    )
    return


@app.cell
def _(mo):
    min_mag = mo.ui.slider(4.0, 8.0, step=0.1, value=5.5, label="Min magnitude")
    days = mo.ui.slider(1, 365, value=90, label="Window (last N days)")
    mo.hstack([min_mag, days])
    return days, min_mag


@app.cell
async def _(days, min_mag):
    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"
    )
    params = urllib.parse.urlencode(
        {
            "filter": f"mag >= {min_mag.value} AND published_at > TIMESTAMP('{since}')",
            "sortby": "-mag",
            "limit": 100,
        }
    )
    url = f"{BASE}/collections/adam.adam_eq_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 = ["published_at", "mag", "mmi", "depth", "place", "iso3"]
    df_view = df[[c for c in cols if c in df.columns]]
    df_view
    return df, df_view


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

    fig, ax = plt.subplots(figsize=(7, 3))
    df["mag"].plot.hist(bins=25, ax=ax, color="#d32f2f", edgecolor="white")
    ax.set_xlabel("Magnitude")
    ax.set_ylabel("Events")
    ax.set_title(f"Magnitude distribution — {len(df)} events")
    fig
    return (fig,)


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