"""
Kathmandu air quality: one year of hourly data, analysed with pandas.

Data: Open-Meteo Air Quality API (CAMS global model, about 40 km grid).
These are modelled values for the area, not readings from a ground station.

Run:  python kathmandu_air.py            -> writes data.json next to this file
"""
import json
import time
import urllib.parse
import urllib.request
from pathlib import Path

import pandas as pd

START, END = "2025-11-01", "2026-10-31"          # the last 12 full months
CITIES = {                                       # name: (lat, lon)
    "Kathmandu": (27.7172, 85.3240),
    "Pokhara": (28.2096, 83.9856),
    "Biratnagar": (26.4525, 87.2718),
    "Nepalgunj": (28.0500, 81.6167),
}
WHO_24H_PM25 = 15        # WHO 2021 guideline for 24-hour mean PM2.5, µg/m³
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

# US EPA AQI bands
BANDS = [(50, "Good"), (100, "Moderate"), (150, "Unhealthy for sensitive groups"),
         (200, "Unhealthy"), (300, "Very unhealthy"), (10_000, "Hazardous")]


def fetch(lat: float, lon: float) -> pd.DataFrame:
    """Download hourly PM2.5, PM10, NO2 and US AQI for one place, in Nepal time."""
    q = urllib.parse.urlencode({
        "latitude": lat, "longitude": lon, "start_date": START, "end_date": END,
        "hourly": "pm2_5,pm10,nitrogen_dioxide,us_aqi", "timezone": "Asia/Kathmandu",
    })
    url = "https://air-quality-api.open-meteo.com/v1/air-quality?" + q
    for attempt in range(3):
        try:
            with urllib.request.urlopen(url, timeout=60) as r:
                h = json.load(r)["hourly"]
            break
        except Exception:
            if attempt == 2:
                raise
            time.sleep(3)
    df = pd.DataFrame(h)
    df["time"] = pd.to_datetime(df["time"])
    return df.set_index("time").dropna(how="all")


def band(aqi: float) -> str:
    return next(name for limit, name in BANDS if aqi <= limit)


def r1(x) -> float:
    return round(float(x), 1)


def main() -> None:
    frames = {city: fetch(*ll) for city, ll in CITIES.items()}
    ktm = frames["Kathmandu"]

    # ---- daily means and the WHO guideline -------------------------------------------
    daily = ktm.resample("D").mean(numeric_only=True)
    days_over_who = int((daily["pm2_5"] > WHO_24H_PM25).sum())
    worst = daily["pm2_5"].nlargest(5)
    cleanest = daily["pm2_5"].nsmallest(1)

    # ---- by month: mean PM2.5 and share of hours in each AQI band ---------------------
    ktm = ktm.assign(month=ktm.index.month, hour=ktm.index.hour, dow=ktm.index.day_of_week,
                     band=ktm["us_aqi"].map(band))
    order = [m for m in pd.date_range(START, END, freq="MS").month]
    monthly = ktm.groupby("month")["pm2_5"].mean().reindex(order)
    band_share = (ktm.groupby("month")["band"].value_counts(normalize=True)
                  .unstack(fill_value=0).reindex(order).fillna(0) * 100)
    for _, name in BANDS:
        if name not in band_share:
            band_share[name] = 0.0

    # ---- by hour of day: dry season (Nov-Apr) vs monsoon (Jun-Sep) -------------------
    dry = ktm[ktm["month"].isin([11, 12, 1, 2, 3, 4])].groupby("hour")["pm2_5"].mean()
    wet = ktm[ktm["month"].isin([6, 7, 8, 9])].groupby("hour")["pm2_5"].mean()

    # ---- by weekday -------------------------------------------------------------------
    weekday = ktm.groupby("dow")["pm2_5"].mean()

    # ---- cities -----------------------------------------------------------------------
    cities = []
    for city, df in frames.items():
        d = df.resample("D").mean(numeric_only=True)
        cities.append({"city": city, "pm25_mean": r1(df["pm2_5"].mean()),
                       "days_over_who": int((d["pm2_5"] > WHO_24H_PM25).sum()),
                       "worst_month": MONTHS[int(df["pm2_5"].groupby(df.index.month).mean().idxmax()) - 1],
                       "aqi_unhealthy_hours_pct": r1((df["us_aqi"] > 150).mean() * 100)})
    cities.sort(key=lambda c: -c["pm25_mean"])

    worst_m = int(monthly.idxmax()); best_m = int(monthly.idxmin())
    peak_hour = int(dry.idxmax()); low_hour = int(dry.idxmin())
    out = {
        "period": {"start": START, "end": END, "hours": int(len(ktm)), "days": int(len(daily))},
        "source": "Open-Meteo Air Quality API (CAMS global model)",
        "who_24h_pm25": WHO_24H_PM25,
        "headline": {
            "pm25_mean": r1(ktm["pm2_5"].mean()),
            "days_over_who": days_over_who,
            "days_over_who_pct": r1(days_over_who / len(daily) * 100),
            "worst_month": MONTHS[worst_m - 1], "worst_month_pm25": r1(monthly[worst_m]),
            "best_month": MONTHS[best_m - 1], "best_month_pm25": r1(monthly[best_m]),
            "worst_vs_best": r1(monthly[worst_m] / monthly[best_m]),
            "dry_peak_hour": peak_hour, "dry_peak_pm25": r1(dry[peak_hour]),
            "dry_low_hour": low_hour, "dry_low_pm25": r1(dry[low_hour]),
            "unhealthy_hours_pct": r1((ktm["us_aqi"] > 150).mean() * 100),
            "max_aqi": int(ktm["us_aqi"].max()),
        },
        "monthly": [{"month": MONTHS[m - 1], "pm25": r1(monthly[m]),
                     "bands": {name: r1(band_share.loc[m, name]) for _, name in BANDS}} for m in order],
        "hourly": {"dry": [r1(v) for v in dry.reindex(range(24))], "wet": [r1(v) for v in wet.reindex(range(24))]},
        "weekday": [{"day": DAYS[i], "pm25": r1(weekday[i])} for i in range(7)],
        "worst_days": [{"date": d.strftime("%Y-%m-%d"), "pm25": r1(v)} for d, v in worst.items()],
        "cleanest_day": {"date": cleanest.index[0].strftime("%Y-%m-%d"), "pm25": r1(cleanest.iloc[0])},
        "cities": cities,
    }
    path = Path(__file__).with_name("data.json")
    path.write_text(json.dumps(out, indent=1), encoding="utf-8")
    h = out["headline"]
    print(f"{out['period']['hours']} hours analysed -> {path.name}")
    print(f"Mean PM2.5 {h['pm25_mean']} µg/m³; {h['days_over_who']} of {out['period']['days']} days over WHO 24h guideline")
    print(f"Worst month {h['worst_month']} ({h['worst_month_pm25']}), best {h['best_month']} ({h['best_month_pm25']}), ratio {h['worst_vs_best']}x")
    print(f"Dry-season peak at {peak_hour}:00 ({h['dry_peak_pm25']}), low at {low_hour}:00 ({h['dry_low_pm25']})")
    print("Cities:", ", ".join(f"{c['city']} {c['pm25_mean']}" for c in cities))
    print("Worst days:", ", ".join(f"{d['date']} {d['pm25']}" for d in out["worst_days"]))


if __name__ == "__main__":
    main()
