#!/usr/bin/env python
"""
HRRR sounding via Herbie:
- User chooses lat/lon and UTC date/hour
- Gets surface elevation automatically (Open-Meteo/USGS) or asks user
- Downloads HRRR pressure-level fields (prs product)
- Computes Td, mixing ratio, theta, theta-e, theta-v
- Saves UW-style sounding file and Skew-T PNG
- Defines parcel at the actual surface pressure (site elevation) and lifts it to 100 hPa
- Computes CAPE, DCAPE, CIN, LCL, LFC, EL
- Only outputs/plots data from site elevation upward (geopotential height >= surface elevation) and down to 100 hPa
-
-
- How to install dependencies Using Colab from Google:
- Make a new directory in colab.
- Add a code cell.
- Copy and paste the following line into the colab cell.
- !apt-get update && apt-get install -y libeccodes0
- Run this cell.
- Add a second code cell.
- Copy and paste the following into this cell.
- !pip install herbie-data cfgrib xarray metpy pandas matplotlib
- Add another code cell in colab.
- Copy and paste this script into the cell.
- Run it.  
-
-
- Alternatively, use wget to get the script from the website.
- !wget https://www.patarnott.com/atms411/general/class2026/HRRRsounding_2.py
- %run HRRRsounding_2.py
"""

import os
import sys
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from herbie import Herbie
import xarray as xr
import metpy.calc as mpcalc
from metpy.plots import SkewT
from metpy.units import units

def get_surface_elevation(lat, lon):
    """Try Open-Meteo elevation service first, then USGS EPQS, fallback to user input."""
    # Attempt 1: Open-Meteo (Fast and highly reliable)
    try:
        url_om = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
        r_om = requests.get(url_om, timeout=10)
        r_om.raise_for_status()
        data_om = r_om.json()
        
        if "elevation" in data_om and isinstance(data_om["elevation"], list):
            elev = float(data_om["elevation"][0])
            print(f"Retrieved surface elevation: {elev:.1f} m (via Open-Meteo)")
            return elev
        else:
            raise ValueError("Unexpected Open-Meteo API JSON structure.")
    except Exception as e1:
        print(f"Open-Meteo API failed ({e1}). Attempting USGS fallback...")
        
        # Attempt 2: USGS EPQS (Older, prone to timeouts and structure changes)
        try:
            url_usgs = f"https://epqs.nationalmap.gov/v1/json?x={lon}&y={lat}&units=Meters&wkid=4326"
            r_usgs = requests.get(url_usgs, timeout=10)
            r_usgs.raise_for_status()
            data_usgs = r_usgs.json()
            
            if "value" in data_usgs and isinstance(data_usgs["value"], (str, int, float)):
                elev = float(data_usgs["value"])
            elif "value" in data_usgs and isinstance(data_usgs["value"], dict) and "elevation" in data_usgs["value"]:
                elev = float(data_usgs["value"]["elevation"])
            else:
                raise ValueError("Unexpected USGS API JSON structure.")
                
            if elev < -1000:
                raise ValueError(f"Invalid elevation returned (likely over ocean): {elev}")
                
            print(f"Retrieved surface elevation: {elev:.1f} m (via USGS)")
            return elev
        except Exception as e2:
            print(f"USGS API also failed ({e2}).")
            
            # Attempt 3: Manual User Input
            try:
                elev_str = input("APIs unavailable. Enter surface elevation in meters manually: ").strip()
                return float(elev_str)
            except Exception as e3:
                print(f"Invalid manual input. Defaulting to 0 meters. Error: {e3}")
                return 0.0

def main():
    # -----------------------------
    # User input
    # -----------------------------
    print("Enter location and UTC time for HRRR sounding:")
    try:
        lat = float(input("Latitude (e.g., 39.0968): ").strip())
        lon = float(input("Longitude (e.g., -120.0324): ").strip())
        date_str = input("Date (YYYY-MM-DD, e.g., 2025-06-21): ").strip()
        hour_str = input("Hour UTC (00-23, e.g., 19): ").strip()
        timestamp = f"{date_str} {int(hour_str):02d}:00"
        dt = pd.to_datetime(timestamp)
    except Exception as e:
        print("Input error:", e)
        sys.exit(1)

    # Surface elevation
    surface_elev = get_surface_elevation(lat, lon)

    # -----------------------------
    # Herbie setup
    # -----------------------------
    save_dir = os.path.join(os.path.expanduser("~"), "data", "hrrr")
    os.makedirs(save_dir, exist_ok=True)
    H = Herbie(timestamp, model="hrrr", product="prs", fxx=0, save_dir=save_dir)

    # -----------------------------
    # Fetch essential fields efficiently
    # -----------------------------
    # Use wgrib2 search string to grab ONLY pressure levels via HTTP range requests
    search_str = ":(TMP|UGRD|VGRD|RH|HGT|SPFH):[0-9]+ mb"
    try:
        ds_all = H.xarray(search_str)
    except Exception as e:
        raise RuntimeError(f"Failed to fetch HRRR data. Verify time and installation. Error: {e}")

    if isinstance(ds_all, list):
        ds_all = xr.merge(ds_all, compat="override", join="inner")

    # Rename cfgrib standard short names to expected script variables
    rename_dict = {}
    for old, new in [("t", "T"), ("u", "u"), ("v", "v"), ("r", "RH"), ("gh", "gh"), ("q", "q")]:
        if old in ds_all.data_vars:
            rename_dict[old] = new
    if rename_dict:
        ds_all = ds_all.rename(rename_dict)

    if "T" not in ds_all or "u" not in ds_all or "v" not in ds_all:
        raise RuntimeError("Missing essential fields (T, u, v). Try a different cycle/time.")

    # -----------------------------
    # Nearest gridpoint on 2D lat/lon
    # -----------------------------
    lat_name = "latitude" if "latitude" in ds_all else ("lat" if "lat" in ds_all else None)
    lon_name = "longitude" if "longitude" in ds_all else ("lon" if "lon" in ds_all else None)
    y_name = "y" if "y" in ds_all.dims else ("Y" if "Y" in ds_all.dims else None)
    x_name = "x" if "x" in ds_all.dims else ("X" if "X" in ds_all.dims else None)
    if any(n is None for n in [lat_name, lon_name, y_name, x_name]):
        raise KeyError("Could not locate 2D latitude/longitude or grid dims (y/x) in dataset.")

    lats = ds_all[lat_name].values
    lons = ds_all[lon_name].values
    target_lon = lon % 360 if np.nanmax(lons) > 180 else lon
    dist2 = (lats - lat) ** 2 + (lons - target_lon) ** 2
    iy, ix = np.unravel_index(np.nanargmin(dist2), dist2.shape)
    pt = ds_all.isel(**{y_name: iy, x_name: ix})

    # -----------------------------
    # Extract base vertical profile
    # -----------------------------
    p_name = "isobaricInhPa"
    if p_name not in pt.coords:
        raise RuntimeError(f"Pressure coordinate '{p_name}' not found in dataset.")
    p = pt[p_name].values * units.hPa
    T = pt["T"].values * units.kelvin
    u = pt["u"].values * units("m/s")
    v = pt["v"].values * units("m/s")

    # Humidity
    if "RH" in pt:
        RH = (pt["RH"].values / 100.0) * units.dimensionless
    elif "q" in pt:
        q = pt["q"].values * units("kg/kg")
        w_from_q = (q / (1.0 * units.dimensionless - q)).to("kg/kg")
        p_pa = p.to("Pa")
        e = (w_from_q * p_pa) / (0.622 * units.dimensionless + w_from_q)
        es = mpcalc.saturation_vapor_pressure(T).to("Pa")
        RH = (e / es).to("dimensionless")
    else:
        raise RuntimeError("Neither RH nor q available; cannot compute humidity.")

    RH = np.clip(RH.magnitude, 0.0, 1.0) * units.dimensionless
    Td = mpcalc.dewpoint_from_relative_humidity(T, RH)
    w = mpcalc.mixing_ratio_from_relative_humidity(p, T, RH).to("g/kg")

    # Geopotential height
    if "gh" in pt:
        z = pt["gh"].values 
    else:
        Tv_for_z = T * (1.0 + 0.61 * w.to("kg/kg"))
        z = np.zeros_like(p.magnitude)
        Rd, g0 = 287.0, 9.80665
        for i in range(1, len(p)):
            Tv_mean = 0.5 * (Tv_for_z[i - 1] + Tv_for_z[i])
            z[i] = z[i - 1] + (Rd * Tv_mean / g0) * np.log(p[i - 1].magnitude / p[i].magnitude)

    # -----------------------------
    # Clip profile
    # -----------------------------
    mask_clip = (z >= surface_elev) & (p.magnitude >= 100.0)
    if not np.any(mask_clip):
        raise RuntimeError("No HRRR pressure levels found above the site elevation with pressure >= 100 hPa.")

    p, T, Td, u, v, RH, w, z = p[mask_clip], T[mask_clip], Td[mask_clip], u[mask_clip], v[mask_clip], RH[mask_clip], w[mask_clip], z[mask_clip]

    # -----------------------------
    # Thermodynamic potentials and wind diagnostics
    # -----------------------------
    theta = mpcalc.potential_temperature(p, T)
    theta_e = mpcalc.equivalent_potential_temperature(p, T, Td)
    Tv = T * (1.0 + 0.61 * w.to("kg/kg"))
    theta_v = mpcalc.potential_temperature(p, Tv)
    drct = (np.degrees(np.arctan2(-u.magnitude, -v.magnitude)) + 360.0) % 360.0
    sped = np.sqrt(u**2 + v**2).to("m/s")

    df = pd.DataFrame({
        "PRES": p.magnitude,
        "HGHT": z,
        "TEMP": T.to("degC").magnitude,
        "DWPT": Td.to("degC").magnitude,
        "RELH": (RH.magnitude * 100.0),
        "MIXR": w.magnitude,
        "DRCT": drct,
        "SPED": sped.magnitude,
        "THTA": theta.magnitude,
        "THTE": theta_e.magnitude,
        "THTV": theta_v.magnitude,
    }).sort_values(by="PRES", ascending=False).reset_index(drop=True)

    # -----------------------------
    # Parcel Diagnostics & DCAPE
    # -----------------------------
    p_prof = (df["PRES"].values * units.hPa)
    T_env_prof = (df["TEMP"].values * units.degC)
    Td_env_prof = (df["DWPT"].values * units.degC)

    T_sfc = df["TEMP"].iloc[0] * units.degC
    Td_sfc = df["DWPT"].iloc[0] * units.degC

    parcel_prof = mpcalc.parcel_profile(p_prof, T_sfc, Td_sfc)

    cape, cin = mpcalc.cape_cin(p_prof, T_env_prof, Td_env_prof, parcel_prof)
    p_lcl, T_lcl = mpcalc.lcl(p_prof[0], T_sfc, Td_sfc)
    lfc_p, _ = mpcalc.lfc(p_prof, T_env_prof, Td_env_prof, parcel_prof)
    el_p, _ = mpcalc.el(p_prof, T_env_prof, Td_env_prof, parcel_prof)

    # Calculate DCAPE (requires MetPy >= 1.4)
    try:
        dcape, _, _ = mpcalc.downdraft_cape(p_prof, T_env_prof, Td_env_prof)
    except Exception:
        dcape = np.nan * units("J/kg")

    pres_full, hght_full = df["PRES"].values, df["HGHT"].values
    pres_asc, hght_asc = pres_full[::-1], hght_full[::-1]

    def p_to_z(p_hpa):
        try:
            val = p_hpa.magnitude
            if np.isnan(val): return np.nan * units.meter
            return float(np.interp(val, pres_asc, hght_asc)) * units.meter
        except Exception:
            return np.nan * units.meter

    lcl_z, lfc_z, el_z = p_to_z(p_lcl), p_to_z(lfc_p), p_to_z(el_p)

    def fmt_qty(q, fmt=".1f"):
        try:
            val = q.magnitude
            return "NaN" if np.isnan(val) else format(val, fmt)
        except Exception:
            return "NaN"

    # -----------------------------
    # Save UW-format text file
    # -----------------------------
    txt_name = f"HRRR_sounding_{dt.strftime('%Y%m%d_%H')}Z_{lat:.3f}_{lon:.3f}.txt"
    with open(txt_name, "w", encoding="utf-8") as f:
        f.write(f"Observations,for,Model,HRRR,at,{dt.strftime('%H')},UTC,{dt.day},{dt.strftime('%b')},{dt.year},,,\n\n")
        f.write(f"Model derived sounding at lat: {lat:.4f}, lon: {lon:.4f}\n")
        f.write(f"Surface elevation (m): {surface_elev:.1f}\n\n")
        f.write("----------------------------------------------------------------------------- \n")
        f.write(",PRES,HGHT,TEMP,DWPT,RELH,MIXR,DRCT,SPED,THTA,THTE,THTV\n")
        f.write(",hPa,m,C,C,%,g/kg,deg,m/s,K,K,K\n")
        f.write("----------------------------------------------------------------------------- \n")
        for _, row in df.iterrows():
            f.write(f",{row['PRES']:.1f},{row['HGHT']:.1f},{row['TEMP']:.1f},{row['DWPT']:.1f},"
                    f"{row['RELH']:.0f},{row['MIXR']:.2f},{row['DRCT']:.0f},{row['SPED']:.1f},"
                    f"{row['THTA']:.1f},{row['THTE']:.0f},{row['THTV']:.1f}\n")
        f.write("----------------------------------------------------------------------------- \n")
        f.write("Parcel diagnostics:\n")
        f.write("- Parcel origin: Actual surface (site elevation)\n")
        f.write(f"- Surface (hPa,m): {df.loc[0, 'PRES']:.1f}, {df.loc[0, 'HGHT']:.1f}\n")
        f.write(f"- CAPE (J/kg): {fmt_qty(cape)}\n")
        f.write(f"- DCAPE (J/kg): {fmt_qty(dcape)}\n")
        f.write(f"- CIN (J/kg): {fmt_qty(cin)}\n")
        f.write(f"- LCL (hPa,m): {fmt_qty(p_lcl)}, {fmt_qty(lcl_z)}\n")
        f.write(f"- LFC (hPa,m): {fmt_qty(lfc_p)}, {fmt_qty(lfc_z)}\n")
        f.write(f"- EL (hPa,m): {fmt_qty(el_p)}, {fmt_qty(el_z)}\n")
    print(f"UW-style sounding saved: {os.path.abspath(txt_name)}")

    # -----------------------------
    # Skew-T plot
    # -----------------------------
    dir_rad = np.deg2rad(df["DRCT"].values)
    u_barb = (-df["SPED"].values * np.sin(dir_rad)) * units("m/s")
    v_barb = (-df["SPED"].values * np.cos(dir_rad)) * units("m/s")

    fig = plt.figure(figsize=(8, 10))
    skew = SkewT(fig)

    skew.plot(df["PRES"].values * units.hPa, df["TEMP"].values * units.degC, color="k", linewidth=2.5, label="Temperature")
    skew.plot(df["PRES"].values * units.hPa, df["DWPT"].values * units.degC, color="k", linewidth=2.5, linestyle="--", label="Dewpoint")
    skew.plot(p_prof, parcel_prof, color="purple", linewidth=3.0, label="Parcel")
    skew.plot_barbs(df["PRES"].values * units.hPa, u_barb, v_barb)

    for method in ["plot_dry_adiabats", "add_dry_adiabats", "plot_moist_adiabats", "add_moist_adiabats", "plot_mixing_lines", "add_mixing_lines"]:
        if hasattr(skew, method):
            getattr(skew, method)(linewidth=0.5)

    skew.ax.set_ylim(df["PRES"].max(), 100)
    skew.ax.set_xlim(-40, 50)
    plt.title(
        f"HRRR Skew-T at {lat:.3f}, {lon:.3f} on {dt.strftime('%Y-%m-%d %H')}Z\n"
        f"Surface elevation {surface_elev:.0f} m  "
        f"CAPE={fmt_qty(cape, '.0f')}  DCAPE={fmt_qty(dcape, '.0f')}  CIN={fmt_qty(cin, '.0f')}",
        fontsize=12
    )
    plt.legend(loc="best")
    plt.tight_layout()
    png_name = f"HRRR_skewt_{dt.strftime('%Y%m%d_%H')}Z_{lat:.3f}_{lon:.3f}.png"
    plt.savefig(png_name, dpi=300)
    plt.show()

    print("\nDiagnostics (parcel from actual surface):")
    print(f"CAPE: {fmt_qty(cape)} J/kg")
    print(f"DCAPE: {fmt_qty(dcape)} J/kg")
    print(f"CIN: {fmt_qty(cin)} J/kg")
    print(f"LCL: {fmt_qty(p_lcl)} hPa, {fmt_qty(lcl_z)} m")
    print(f"LFC: {fmt_qty(lfc_p)} hPa, {fmt_qty(lfc_z)} m")
    print(f"EL: {fmt_qty(el_p)} hPa, {fmt_qty(el_z)} m")

if __name__ == "__main__":
    main()
