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

        Pick a country (ISO3) and a minimum population impact — the flood events
        are ranked by affected population.
        """
    )
    return


@app.cell
def _(mo):
    iso3 = mo.ui.text(value="BGD", label="ISO3 country code")
    min_pop = mo.ui.slider(0, 1_000_000, step=10_000, value=50_000, label="Min population affected")
    mo.hstack([iso3, min_pop])
    return iso3, min_pop


@app.cell
async def _(iso3, min_pop):
    import urllib.parse

    BASE = "https://api.adam.geospatial.wfp.org/api"
    filter_expr = f"iso3 = '{iso3.value.upper()}' AND fl_popn >= {min_pop.value}"
    params = urllib.parse.urlencode(
        {"filter": filter_expr, "sortby": "-fl_popn", "limit": 100}
    )
    url = f"{BASE}/collections/adam.adam_fl_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 = [
        "country",
        "iso3",
        "effective",
        "cleared",
        "fl_popn",
        "fl_croplnd",
        "flood_area",
    ]
    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 "fl_popn" in df and len(df):
        fig, ax = plt.subplots(figsize=(7, 3))
        top = df.nlargest(10, "fl_popn").sort_values("fl_popn")
        top.plot.barh(
            x="effective", y="fl_popn", ax=ax, color="#1565c0", legend=False
        )
        ax.set_xlabel("Population affected")
        ax.set_ylabel("Flood event (effective date)")
        ax.set_title(f"Top 10 floods in {df['iso3'].iloc[0] if len(df) else ''} by affected population")
        fig
    return


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