#!/usr/bin/env python3
"""Build the Canada mean-annual precipitation d18O isoscape (detrended interpolation).

Method (Bowen & Wilkinson 2002; Bowen & Revenaugh 2003; Delavau et al. 2014):
  1. precipitation-weighted annual mean d18O per station
  2. multiple regression on latitude, elevation, mean annual temperature
     and mean annual precipitation (predictors from WorldClim 2.1, 10 arc-min)
  3. ordinary kriging of the regression residuals (exponential variogram)
  4. prediction = regression surface + kriged residuals, on a 10 km
     EPSG:3347 grid masked to Canada
  5. leave-one-out validation (refit + re-krige per station)

Outputs (output/):
  d18o_pred.tif  - predicted mean annual precipitation d18O (permil), EPSG:3347
  d18o_se.tif    - kriging standard error (permil), EPSG:3347
  stations.gpkg  - station points with observed / predicted / LOO values, EPSG:4326
  model.json     - regression coefficients, variogram, LOO R2 and RMSE

Only numpy / scipy / osgeo are used (no sklearn, no pykrige).
"""
import json, math, os, sys
import numpy as np
from scipy.optimize import curve_fit
from scipy.spatial import cKDTree
from osgeo import gdal, ogr, osr

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, "output")
DATA = os.path.join(BASE, "data")
GRID = json.load(open(os.path.join(OUT, "grid.json")))
RES = GRID.get("res_m", GRID.get("res"))


def log(*a):
    print(*a, flush=True)


# ---------------------------------------------------------------- predictors
def sample_grid(path, xs, ys):
    """Sample a 3347 raster at projected coordinates xs, ys (arrays)."""
    ds = gdal.Open(path)
    gt = ds.GetGeoTransform()
    band = ds.GetRasterBand(1)
    nodata = band.GetNoDataValue()
    arr = band.ReadAsArray()
    col = ((np.asarray(xs) - gt[0]) / gt[1]).astype(int)
    row = ((np.asarray(ys) - gt[3]) / gt[5]).astype(int)
    ok = (col >= 0) & (col < arr.shape[1]) & (row >= 0) & (row < arr.shape[0])
    vals = np.full(len(xs), np.nan)
    vals[ok] = arr[row[ok], col[ok]]
    if nodata is not None:
        vals[vals == nodata] = np.nan
    ds = None
    return vals


def lonlat_to_3347(lon, lat):
    s4326 = osr.SpatialReference(); s4326.ImportFromEPSG(4326)
    s4326.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    s3347 = osr.SpatialReference(); s3347.ImportFromEPSG(3347)
    s3347.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    ct = osr.CoordinateTransformation(s4326, s3347)
    pts = np.array(ct.TransformPoints(list(zip(np.atleast_1d(lon), np.atleast_1d(lat)))))
    return pts[:, 0], pts[:, 1]


def load_predictor_grids():
    """Return dict of 2D arrays (ny, nx) on the analysis grid.

    WorldClim cells over the ocean are nodata; coastal land cells next to
    them would otherwise have no predictor value. Nodata is therefore
    filled from the nearest valid cell (distance transform) — the standard
    treatment, and the fill only ever reaches a few cells inland.
    """
    from scipy.ndimage import distance_transform_edt

    def fill(arr):
        mask = np.isfinite(arr)
        _, inds = distance_transform_edt(~mask, return_indices=True)
        return arr[tuple(inds)]

    def read(path):
        ds = gdal.Open(path)
        a = ds.GetRasterBand(1).ReadAsArray().astype(float)
        nd = ds.GetRasterBand(1).GetNoDataValue()
        if nd is not None:
            a[a == nd] = np.nan
        return a
    # WorldClim 2.1 GeoTIFFs store bio1 in degrees C directly (verified:
    # Victoria 9.8 C, Ottawa 5.8 C, Alert -19.1 C) — NOT C x 10 as the
    # older .bil files did. Do not divide by 10.
    bio1 = fill(read(os.path.join(OUT, "bio1_3347.tif")))          # deg C
    bio12 = fill(read(os.path.join(OUT, "bio12_3347.tif")))       # mm / yr
    elev = fill(read(os.path.join(OUT, "elev_3347.tif")))         # m
    mask = read(os.path.join(OUT, "canada_mask_3347.tif")) > 0
    return dict(bio1=bio1, bio12=bio12, elev=elev, mask=mask)


def design(lat, elev_m, mat_c, map_mm):
    """Regression design matrix. Scaling keeps the normal equations conditioned."""
    return np.column_stack([
        np.ones_like(lat),
        lat,
        np.asarray(elev_m) / 1000.0,
        np.asarray(mat_c),
        np.asarray(map_mm) / 1000.0,
    ])


PRED_NAMES = ["intercept", "latitude_deg", "elevation_km", "mean_annual_temp_C",
              "annual_precip_m"]


# ---------------------------------------------------------------- variogram
def exp_variogram(h, nugget, sill, rng):
    return nugget + sill * (1.0 - np.exp(-h / rng))


def fit_variogram(xy, resid, max_dist=2_500_000, nbins=12):
    """Empirical semivariogram of residuals; fit exponential model."""
    tree = cKDTree(xy)
    pairs = tree.query_pairs(max_dist)
    if not pairs:
        raise RuntimeError("no station pairs within max_dist")
    i = np.array([p[0] for p in pairs]); j = np.array([p[1] for p in pairs])
    d = np.linalg.norm(xy[i] - xy[j], axis=1)
    g = 0.5 * (resid[i] - resid[j]) ** 2
    edges = np.linspace(0, max_dist, nbins + 1)
    bc, gv, n = [], [], []
    for b in range(nbins):
        m = (d >= edges[b]) & (d < edges[b + 1])
        if m.sum() >= 10:
            bc.append(d[m].mean()); gv.append(g[m].mean()); n.append(int(m.sum()))
    bc = np.array(bc); gv = np.array(gv)
    var = float(np.var(resid))
    p0 = [0.05 * var, 0.9 * var, 800_000.0]
    bounds = ([0, 0, 50_000], [var, 5 * var, 10_000_000])
    popt, _ = curve_fit(exp_variogram, bc, gv, p0=p0, bounds=bounds, maxfev=20000)
    return dict(nugget=float(popt[0]), sill=float(popt[1]), range_m=float(popt[2]),
                bins=[dict(dist_m=float(a), gamma=float(b), n=int(c)) for a, b, c in zip(bc, gv, n)])


# ---------------------------------------------------------------- kriging
def krige_predict(xy, resid, variogram, targets, k=20, max_dist=2_000_000):
    """Ordinary kriging of residuals at target points.

    Returns (prediction, kriging standard error). Targets with no station
    within max_dist get prediction 0 and SE = sqrt(total sill) (i.e. the
    regression surface alone, with full residual variance).
    """
    nugget, sill, rng = variogram["nugget"], variogram["sill"], variogram["range_m"]
    total = nugget + sill
    tree = cKDTree(xy)
    dists, idx = tree.query(targets, k=min(k, len(xy)), distance_upper_bound=max_dist)
    if dists.ndim == 1:
        dists = dists[:, None]; idx = idx[:, None]
    n = len(targets)
    pred = np.zeros(n); se = np.full(n, math.sqrt(total))
    for t in range(n):
        m = np.isfinite(dists[t]) & (idx[t] < len(xy))
        if m.sum() < 3:
            continue
        ii = idx[t][m]; dd = dists[t][m]
        # covariance between stations: C(h) = sill*exp(-h/range); diagonal adds nugget
        D = np.linalg.norm(xy[ii][:, None, :] - xy[ii][None, :, :], axis=2)
        C = sill * np.exp(-D / rng)
        np.fill_diagonal(C, sill + nugget)
        # covariance station -> target
        c0 = sill * np.exp(-dd / rng)
        # ordinary kriging system with Lagrange multiplier
        A = np.zeros((len(ii) + 1, len(ii) + 1))
        A[:len(ii), :len(ii)] = C
        A[:len(ii), -1] = 1.0; A[-1, :len(ii)] = 1.0
        b = np.concatenate([c0, [1.0]])
        try:
            w = np.linalg.solve(A, b)
        except np.linalg.LinAlgError:
            w = np.linalg.lstsq(A, b, rcond=None)[0]
        lam = w[:len(ii)]
        pred[t] = float(lam @ resid[ii])
        var = total - float(lam @ c0) - float(w[-1])
        se[t] = math.sqrt(max(var, 0.0))
    return pred, se


# ---------------------------------------------------------------- main
def main(stations_csv):
    import csv
    rows = list(csv.DictReader(open(stations_csv)))
    log(f"stations in file: {len(rows)}")
    st = [r for r in rows if r.get("d18o") not in (None, "", "NA")]
    log(f"stations with annual d18O: {len(st)}")
    lon = np.array([float(r["lon"]) for r in st])
    lat = np.array([float(r["lat"]) for r in st])
    obs = np.array([float(r["d18o"]) for r in st])
    x, y = lonlat_to_3347(lon, lat)
    # sample predictors from the filled grids (nodata filled from nearest
    # valid cell, so coastal stations keep their values)
    P0 = load_predictor_grids()

    def sample_arr(arr, xs, ys):
        col = ((np.asarray(xs) - GRID["xmin"]) / RES).astype(int)
        row = ((GRID["ymax"] - np.asarray(ys)) / RES).astype(int)
        ok = (col >= 0) & (col < arr.shape[1]) & (row >= 0) & (row < arr.shape[0])
        vals = np.full(len(xs), np.nan)
        vals[ok] = arr[row[ok], col[ok]]
        return vals

    bio1 = sample_arr(P0["bio1"], x, y)
    bio12 = sample_arr(P0["bio12"], x, y)
    elev = sample_arr(P0["elev"], x, y)
    # fall back to station-reported elevation where the grid has no value
    rep = np.array([float(r["elev_m"]) if r.get("elev_m") not in (None, "", "NA") else np.nan for r in st])
    elev = np.where(np.isnan(elev), rep, elev)
    ok = np.isfinite(bio1) & np.isfinite(bio12) & np.isfinite(elev)
    if not ok.all():
        log(f"WARNING: {(~ok).sum()} stations lack a predictor value; excluded")
    st = [r for r, k in zip(st, ok) if k]
    lon, lat, obs, x, y = lon[ok], lat[ok], obs[ok], x[ok], y[ok]
    bio1, bio12, elev = bio1[ok], bio12[ok], elev[ok]
    X = design(lat, elev, bio1, bio12)
    beta, *_ = np.linalg.lstsq(X, obs, rcond=None)
    fit = X @ beta
    resid = obs - fit
    ss_res = float(np.sum(resid ** 2)); ss_tot = float(np.sum((obs - obs.mean()) ** 2))
    r2 = 1 - ss_res / ss_tot
    rmse_reg = math.sqrt(ss_res / len(obs))
    log(f"regression R2 = {r2:.3f}, RMSE = {rmse_reg:.2f} permil")
    log("coefficients: " + ", ".join(f"{n}={b:.4f}" for n, b in zip(PRED_NAMES, beta)))
    xy = np.column_stack([x, y])
    vario = fit_variogram(xy, resid)
    log(f"variogram: nugget={vario['nugget']:.3f} sill={vario['sill']:.3f} range={vario['range_m']/1000:.0f} km")

    # ---- leave-one-out validation
    loo_pred = np.zeros(len(obs))
    for i in range(len(obs)):
        m = np.ones(len(obs), dtype=bool); m[i] = False
        b_i, *_ = np.linalg.lstsq(X[m], obs[m], rcond=None)
        r_i = obs[m] - X[m] @ b_i
        p, _ = krige_predict(xy[m], r_i, vario, xy[i:i + 1], k=20)
        loo_pred[i] = float(X[i] @ b_i + p[0])
    loo_err = loo_pred - obs
    loo_rmse = math.sqrt(float(np.mean(loo_err ** 2)))
    loo_r2 = 1 - float(np.sum(loo_err ** 2)) / ss_tot
    log(f"LOO: R2 = {loo_r2:.3f}, RMSE = {loo_rmse:.2f} permil (Delavau 2014: R2 0.70-0.72, RMSE 2.76-2.91)")

    # ---- predict on the grid
    P = load_predictor_grids()
    ny, nx = P["mask"].shape
    # Clamp grid precipitation to the range sampled at the stations.
    # The precip coefficient (+3.5 permil per metre) is a
    # maritime/continental proxy, not a causal amount effect, and the grid
    # reaches >4 m/yr on the BC coast — 2.5x beyond any station. Without
    # the clamp the wettest coast predicts -0.5 permil (heavier than any
    # station); with it, -7 to -9 permil, consistent with the Bowen grid.
    # Elevation and temperature are NOT clamped: the altitude effect is
    # physical and ice-core data support light values at high elevation
    # (Mt. Logan modelled -29 permil, cf. ice core ~-30 permil).
    p_lo = float(np.nanmin(bio12)); p_hi = float(np.nanmax(bio12))
    bio12_g = np.clip(P["bio12"], p_lo, p_hi)
    print(f"clamping grid precipitation to station range "
          f"{p_lo:.0f}..{p_hi:.0f} mm/yr")
    ys, xs = np.mgrid[0:ny, 0:nx]
    gx = GRID["xmin"] + (xs + 0.5) * RES
    gy = GRID["ymax"] - (ys + 0.5) * RES
    lat_g = np.full((ny, nx), np.nan)
    # latitude of each grid cell (transform back to 4326)
    s3347 = osr.SpatialReference(); s3347.ImportFromEPSG(3347)
    s3347.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    s4326 = osr.SpatialReference(); s4326.ImportFromEPSG(4326)
    s4326.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
    ct = osr.CoordinateTransformation(s3347, s4326)
    flat = ct.TransformPoints(list(zip(gx.ravel(), gy.ravel())))
    lat_g = np.array(flat)[:, 1].reshape(ny, nx)
    Xg = design(lat_g.ravel(), P["elev"].ravel(), P["bio1"].ravel(),
                bio12_g.ravel())
    reg_g = (Xg @ beta).reshape(ny, nx)
    cells = P["mask"] & np.isfinite(reg_g)
    cy, cx = np.where(cells)
    tx = GRID["xmin"] + (cx + 0.5) * RES
    ty = GRID["ymax"] - (cy + 0.5) * RES
    kr, se = krige_predict(xy, resid, vario, np.column_stack([tx, ty]), k=20)
    pred = np.full((ny, nx), np.nan)
    se_g = np.full((ny, nx), np.nan)
    pred[cy, cx] = reg_g[cy, cx] + kr
    se_g[cy, cx] = se

    def write_tif(path, arr, nodata=-9999.0):
        drv = gdal.GetDriverByName("GTiff")
        ds = drv.Create(path, nx, ny, 1, gdal.GDT_Float32,
                        options=["COMPRESS=DEFLATE", "TILED=YES"])
        ds.SetGeoTransform([GRID["xmin"], RES, 0, GRID["ymax"], 0, -RES])
        s = osr.SpatialReference(); s.ImportFromEPSG(3347)
        ds.SetProjection(s.ExportToWkt())
        b = ds.GetRasterBand(1)
        a = np.where(np.isfinite(arr), arr, nodata).astype(np.float32)
        b.WriteArray(a); b.SetNoDataValue(nodata)
        b.SetDescription("")
        ds = None

    write_tif(os.path.join(OUT, "d18o_pred.tif"), pred)
    write_tif(os.path.join(OUT, "d18o_se.tif"), se_g)
    log("wrote d18o_pred.tif and d18o_se.tif")

    # ---- station GeoPackage (EPSG:4326, per standards)
    gpkg = os.path.join(OUT, "stations.gpkg")
    if os.path.exists(gpkg):
        os.remove(gpkg)
    drv = ogr.GetDriverByName("GPKG")
    ds = drv.CreateDataSource(gpkg)
    lyr = ds.CreateLayer("stations", s4326, ogr.wkbPoint)
    for name, typ in [("station", ogr.OFTString), ("source", ogr.OFTString),
                      ("years", ogr.OFTString), ("n_months", ogr.OFTInteger),
                      ("n_years", ogr.OFTInteger), ("method", ogr.OFTString),
                      ("elev_m", ogr.OFTReal), ("d18o", ogr.OFTReal),
                      ("precip_mm", ogr.OFTReal), ("mat_c", ogr.OFTReal),
                      ("map_mm", ogr.OFTReal), ("resid", ogr.OFTReal),
                      ("loo_pred", ogr.OFTReal), ("loo_err", ogr.OFTReal)]:
        lyr.CreateField(ogr.FieldDefn(name, typ))
    for i, r in enumerate(st):
        f = ogr.Feature(lyr.GetLayerDefn())
        f.SetGeometry(ogr.CreateGeometryFromWkt(f"POINT ({lon[i]} {lat[i]})"))
        f.SetField("station", r.get("station", ""))
        f.SetField("source", r.get("source", ""))
        f.SetField("years", r.get("years", ""))
        f.SetField("n_months", int(float(r["n_months"])) if r.get("n_months") not in (None, "", "NA") else 0)
        f.SetField("n_years", int(float(r["n_years"])) if r.get("n_years") not in (None, "", "NA") else 0)
        f.SetField("method", r.get("method", ""))
        f.SetField("elev_m", float(elev[i]))
        f.SetField("d18o", float(obs[i]))
        f.SetField("precip_mm", float(r["precip_mm"]) if r.get("precip_mm") not in (None, "", "NA") else None)
        f.SetField("mat_c", float(bio1[i]))
        f.SetField("map_mm", float(bio12[i]))
        f.SetField("resid", float(resid[i]))
        f.SetField("loo_pred", float(loo_pred[i]))
        f.SetField("loo_err", float(loo_err[i]))
        lyr.CreateFeature(f)
    ds = None
    log(f"wrote stations.gpkg ({len(st)} stations)")

    model = dict(
        n_stations=len(st),
        regression=dict(coefficients={n: float(b) for n, b in zip(PRED_NAMES, beta)},
                        r2=float(r2), rmse_permil=float(rmse_reg)),
        variogram=vario,
        loo=dict(r2=float(loo_r2), rmse_permil=float(loo_rmse)),
        grid=GRID,
        precip_clamp_mm=[p_lo, p_hi],
        notes="Precipitation-weighted annual mean d18O per station; OLS on latitude, "
              "elevation, WorldClim 2.1 mean annual temperature and annual precipitation; "
              "ordinary kriging of residuals (exponential variogram); 10 km EPSG:3347 grid, "
              "masked to Canada. Grid precipitation clamped to the station-sampled range "
              "(maritime/continental proxy, not a causal amount effect); elevation and "
              "temperature not clamped.",
    )
    json.dump(model, open(os.path.join(OUT, "model.json"), "w"), indent=1)
    log("wrote model.json")
    return model


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(DATA, "stations.csv"))
