#!/usr/bin/env python3
"""Build the Canada precipitation d2H isoscape map (PyQGIS, headless).

Reads output/d2h_pred.tif, output/d2h_se.tif, output/stations_d2h.gpkg and
output/model_d2h.json (produced by model_d2h.py) and exports a 2-page
A1 landscape vector PDF:
  p1  main isoscape map (EPSG:3347, StatCan Lambert), station points,
      legend, scale bar, north arrow, method + sources + validation
  p2  uncertainty map (kriging standard error) + station table + data gaps

Re-runnable: `python3 build_isoscape_map.py` (system python3).
QGIS 3.34.4, Ubuntu noble. Same layout pattern as the Turkiye map.
"""
import json
import math
import os
import sys

os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(BASE, "data")
OUTD = os.path.join(BASE, "output")
OUT = os.path.join(OUTD, "canada-d2h-isoscape.pdf")
FONT = "DejaVu Sans"

from qgis.core import (
    QgsApplication, QgsProject, QgsCoordinateReferenceSystem,
    QgsRectangle, QgsRasterLayer, QgsVectorLayer,
    QgsPrintLayout, QgsLayoutItemPage, QgsLayoutItemMap, QgsLayoutItemLabel,
    QgsLayoutItemScaleBar, QgsLayoutItemPicture, QgsLayoutItemShape,
    QgsLayoutItemLegend, QgsLayoutPoint, QgsLayoutSize, QgsLayoutExporter,
    QgsUnitTypes, QgsLayoutItemMapGrid, QgsFillSymbol, QgsLineSymbol,
    QgsSingleSymbolRenderer, QgsGraduatedSymbolRenderer,
    QgsRendererRange, QgsSymbol, QgsRenderContext,
    QgsSingleBandPseudoColorRenderer, QgsColorRampShader,
    QgsRasterShader, QgsPalLayerSettings, QgsVectorLayerSimpleLabeling,
)
from qgis.PyQt.QtGui import QFont, QColor
from qgis.PyQt.QtCore import Qt

CRS3347 = "EPSG:3347"

# ColourBrewer RdYlBu, blue (very negative d18O) -> red (least negative)
RAMP = ["#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8",
        "#fee090", "#fdae61", "#f46d43", "#d73027"]
SE_RAMP = ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6",
           "#4292c6", "#2171b5", "#08519c", "#08306b"]


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


def qfont(size, bold=False):
    f = QFont(FONT)
    f.setPointSizeF(float(size))
    f.setBold(bold)
    return f


def init_qgis():
    QgsApplication.setPrefixPath("/usr", True)
    app = QgsApplication([], False)
    app.initQgis()
    return app


# ---------------------------------------------------------------- layout helpers
PAGE_Y0 = [0.0]


def new_page(layout, width=841, height=594):
    page = QgsLayoutItemPage(layout)
    page.setPageSize(QgsLayoutSize(width, height, QgsUnitTypes.LayoutMillimeters))
    pc = layout.pageCollection()
    pc.addPage(page)
    PAGE_Y0[0] = pc.pagePositionToAbsolute(
        pc.pageCount() - 1,
        QgsLayoutPoint(0, 0, QgsUnitTypes.LayoutMillimeters)).y()
    return page


def _py(y, absolute):
    return y if absolute else y + PAGE_Y0[0]


def add_label(layout, x, y, w, h, text, size=10, bold=False,
              color=QColor(0, 0, 0), absolute=False):
    y = _py(y, absolute)
    lab = QgsLayoutItemLabel(layout)
    lab.setText(text)
    lab.setFont(qfont(size, bold))
    lab.setFontColor(color)
    lab.setHAlign(Qt.AlignLeft)
    lab.setVAlign(Qt.AlignTop)
    lab.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    lab.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(lab)
    return lab


def add_rect(layout, x, y, w, h, fill="#ffffff", outline="#000000",
             outline_w=0.3, absolute=False):
    y = _py(y, absolute)
    sh = QgsLayoutItemShape(layout)
    sh.setShapeType(QgsLayoutItemShape.Shape.Rectangle)
    sh.setSymbol(QgsFillSymbol.createSimple({
        "color": fill, "outline_color": outline,
        "outline_width": str(outline_w)}))
    sh.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    sh.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(sh)
    return sh


def add_ellipse(layout, x, y, w, h, fill="#ffffff", outline="#000000",
                outline_w=0.3, absolute=False):
    y = _py(y, absolute)
    sh = QgsLayoutItemShape(layout)
    sh.setShapeType(QgsLayoutItemShape.Shape.Ellipse)
    sh.setSymbol(QgsFillSymbol.createSimple({
        "color": fill, "outline_color": outline,
        "outline_width": str(outline_w)}))
    sh.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    sh.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(sh)
    return sh


def legend_rows(layout, x, y, rows, swatch_w=12, swatch_h=5.5, row_h=8,
                size=9):
    """Hand-built legend: (colour, label) rows. A QgsLayoutItemLegend
    stays empty here because the layers are added to the project without
    a layer tree (addMapLayer(..., False)); hand-building is also how the
    Turkiye map does it, and it gives exact control over wording."""
    for i, (color, label) in enumerate(rows):
        ry = y + i * row_h
        add_rect(layout, x, ry, swatch_w, swatch_h, fill=color,
                 outline="#666666", outline_w=0.2)
        add_label(layout, x + swatch_w + 3, ry - 0.5, 250, row_h, label,
                  size=size)
    return y + len(rows) * row_h


def add_map(layout, x, y, w, h, extent, layers, crs):
    y = _py(y, False)
    m = QgsLayoutItemMap(layout)
    m.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    m.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    m.setExtent(extent)
    m.setCrs(crs)
    m.setLayers(layers)
    m.setBackgroundColor(QColor(235, 238, 240))
    layout.addLayoutItem(m)
    return m


def add_grid(m, interval=10.0, font_size=8):
    G = QgsLayoutItemMapGrid
    g = m.grid()
    g.setEnabled(True)
    g.setCrs(QgsCoordinateReferenceSystem("EPSG:4326"))
    g.setIntervalX(interval)
    g.setIntervalY(interval)
    g.setStyle(G.GridStyle.Solid)
    g.setGridLineColor(QColor(255, 255, 255, 110))
    g.setGridLineWidth(0.3)
    g.setAnnotationEnabled(True)
    g.setAnnotationFormat(G.AnnotationFormat.DecimalWithSuffix)
    # Whole degrees only: "170.000°W" is needlessly long, and the longest
    # labels clip at the page edge (the 120°W bottom label loses its tail).
    g.setAnnotationPrecision(0)
    g.setAnnotationFont(qfont(font_size))
    g.setAnnotationFontColor(QColor(40, 40, 40))
    for side in (G.BorderSide.Bottom,):
        g.setAnnotationDisplay(G.DisplayMode.ShowAll, side)
        g.setAnnotationPosition(G.AnnotationPosition.OutsideMapFrame, side)
    # Left (latitude) annotations go INSIDE the frame: outside, they are
    # clipped by the page edge (only 8 mm of margin — the label's tail,
    # "00°W", is all that survives). Inside, they sit over ocean.
    g.setAnnotationDisplay(G.DisplayMode.ShowAll, G.BorderSide.Left)
    g.setAnnotationPosition(G.AnnotationPosition.InsideMapFrame,
                            G.BorderSide.Left)
    for side in (G.BorderSide.Top, G.BorderSide.Right):
        g.setAnnotationDisplay(G.DisplayMode.HideAll, side)


def scalebar_width(m, units_per_seg, segments):
    return segments * units_per_seg * 1e6 / m.scale()


def add_scalebar(layout, m, x, y, units_per_seg=500, segments=4):
    bar_w = scalebar_width(m, units_per_seg, segments)
    panel_w = bar_w + 8
    y = _py(y, False)
    add_rect(layout, x - 4, y - 3, panel_w + 8, 18, fill="255,255,255,230",
             outline="#999999", outline_w=0.25, absolute=True)
    sb = QgsLayoutItemScaleBar(layout)
    sb.setLinkedMap(m)
    sb.setStyle("Single Box")
    sb.setUnits(QgsUnitTypes.DistanceKilometers)
    sb.setUnitsPerSegment(units_per_seg)
    sb.setNumberOfSegments(segments)
    sb.setNumberOfSegmentsLeft(0)
    sb.setUnitLabel("km")
    sb.setFont(qfont(9))
    sb.setHeight(4)
    sb.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    sb.attemptResize(QgsLayoutSize(bar_w + 10, 12, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(sb)
    return sb


def add_north(layout, x, y, w=18, h=32):
    y = _py(y, False)
    add_rect(layout, x - 5, y - 3, w + 10, h + 17, fill="255,255,255,230",
             outline="#999999", outline_w=0.25, absolute=True)
    nlab = QgsLayoutItemLabel(layout)
    nlab.setText("N")
    nlab.setFont(qfont(16, True))
    nlab.setFontColor(QColor(0, 0, 0))
    nlab.setHAlign(Qt.AlignHCenter)
    nlab.setVAlign(Qt.AlignTop)
    nlab.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
    nlab.attemptResize(QgsLayoutSize(w, 12, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(nlab)
    pic = QgsLayoutItemPicture(layout)
    pic.setPicturePath(os.path.join(BASE, "north_arrow.svg"))
    pic.attemptMove(QgsLayoutPoint(x, y + 12, QgsUnitTypes.LayoutMillimeters))
    pic.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(pic)
    return pic


def aspect_rect(rect, aspect):
    w, h = rect.width(), rect.height()
    cx, cy = rect.center().x(), rect.center().y()
    if w / h > aspect:
        nh = w / aspect
        return QgsRectangle(cx - w / 2, cy - nh / 2, cx + w / 2, cy + nh / 2)
    nw = h * aspect
    return QgsRectangle(cx - nw / 2, cy - h / 2, cx + nw / 2, cy + h / 2)


# ---------------------------------------------------------------- layers
def raster_layer(path, name):
    lyr = QgsRasterLayer(path, name)
    if not lyr.isValid():
        raise RuntimeError(f"invalid raster layer: {path}")
    return lyr


def vector_layer(path, name, layer_name=None):
    uri = path + ("|layername=" + layer_name if layer_name else "")
    lyr = QgsVectorLayer(uri, name, "ogr")
    if not lyr.isValid():
        raise RuntimeError(f"invalid vector layer: {path}")
    return lyr


def pseudocolor(lyr, breaks, colors, label_fmt):
    """Discrete pseudocolour renderer with equal classes over breaks."""
    shader = QgsRasterShader()
    ramp = QgsColorRampShader()
    ramp.setColorRampType(QgsColorRampShader.Discrete)
    items = []
    for i in range(len(breaks) - 1):
        it = QgsColorRampShader.ColorRampItem(
            breaks[i + 1], QColor(colors[i]),
            label_fmt.format(lo=breaks[i], hi=breaks[i + 1]))
        items.append(it)
    ramp.setColorRampItemList(items)
    shader.setRasterShaderFunction(ramp)
    ren = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, shader)
    ren.setClassificationMin(breaks[0])
    ren.setClassificationMax(breaks[-1])
    lyr.setRenderer(ren)
    lyr.triggerRepaint()
    return ren


def graduated_points(lyr, field, breaks, colors):
    ranges = []
    for i in range(len(breaks) - 1):
        sym = QgsSymbol.defaultSymbol(lyr.geometryType())
        sym.setColor(QColor(colors[i]))
        sym.symbolLayer(0).setStrokeColor(QColor(0, 0, 0))
        sym.symbolLayer(0).setStrokeWidth(0.3)
        sym.symbolLayer(0).setSize(3.2)
        ranges.append(QgsRendererRange(breaks[i], breaks[i + 1], sym,
                                       f"{breaks[i]:.0f} to {breaks[i + 1]:.0f} ‰"))
    ren = QgsGraduatedSymbolRenderer(field, ranges)
    ren.setMode(QgsGraduatedSymbolRenderer.EqualInterval)
    lyr.setRenderer(ren)
    lyr.triggerRepaint()
    return ren


# ---------------------------------------------------------------- main
def main():
    model = json.load(open(os.path.join(OUTD, "model_d2h.json")))
    n_st = model["n_stations"]
    loo = model["loo"]
    reg = model["regression"]
    vario = model["variogram"]
    log(f"model: n={n_st} LOO R2={loo['r2']:.2f} RMSE={loo['rmse_permil']:.2f} permil")

    app = init_qgis()
    project = QgsProject.instance()
    crs = QgsCoordinateReferenceSystem(CRS3347)
    project.setCrs(crs)

    # --- data range of the prediction raster (for class breaks)
    from osgeo import gdal
    ds = gdal.Open(os.path.join(OUTD, "d2h_pred.tif"))
    band = ds.GetRasterBand(1)
    mn, mx, _, _ = band.GetStatistics(True, True)
    ds = None
    lo = math.floor(mn)
    hi = math.ceil(mx)
    nb = 9
    breaks = [lo + (hi - lo) * i / nb for i in range(nb + 1)]
    log(f"d2H range {mn:.1f} to {mx:.1f} permil; breaks {lo}..{hi}")
    ds = gdal.Open(os.path.join(OUTD, "d2h_se.tif"))
    se_mn, se_mx, _, _ = ds.GetRasterBand(1).GetStatistics(True, True)
    ds = None
    log(f"SE range {se_mn:.2f} to {se_mx:.2f} permil")

    # --- layers
    countries = vector_layer(
        os.path.join(DATA, "ne_countries", "ne_10m_admin_0_countries.shp"),
        "Land (Natural Earth)")
    countries.setSubsetString("")  # whole world, light background
    sym = QgsFillSymbol.createSimple(
        {"color": "#e9e9e9", "outline_color": "#b0b0b0", "outline_width": "0.2"})
    countries.setRenderer(QgsSingleSymbolRenderer(sym))

    pred = raster_layer(os.path.join(OUTD, "d2h_pred.tif"),
                        "Mean annual precipitation δ²H (‰)")
    pseudocolor(pred, breaks, RAMP, "{lo:.0f} to {hi:.0f} ‰")

    se = raster_layer(os.path.join(OUTD, "d2h_se.tif"),
                      "Kriging standard error (‰)")
    # SE range is narrow (6.8–7.4 permil: the flat variogram means the
    # error is dominated by the nugget, not by distance to a station).
    # Use 0.25 permil classes spanning the observed SE range.
    se_lo = math.floor(se_mn * 4) / 4
    se_hi = math.ceil(se_mx * 4) / 4
    se_breaks = [se_lo + i * 0.25 for i in range(int(round((se_hi - se_lo) / 0.25)) + 1)]
    pseudocolor(se, se_breaks, SE_RAMP[:len(se_breaks) - 1], "{lo:.2f} to {hi:.2f} ‰")

    provinces = vector_layer(os.path.join(DATA, "canada_provinces.geojson"),
                             "Province / territory boundary")
    psym = QgsLineSymbol.createSimple(
        {"color": "#666666", "width": "0.4", "line_style": "solid"})
    provinces.setRenderer(QgsSingleSymbolRenderer(psym))

    lakes = vector_layer(
        os.path.join(os.path.dirname(BASE), "turkiye-sites-map", "data",
                     "hydro_lakes", "ne_10m_lakes.shp"), "Lakes (Natural Earth)")
    lsym = QgsFillSymbol.createSimple(
        {"color": "#b8d4e8", "outline_color": "#7fb0d0", "outline_width": "0.2"})
    lakes.setRenderer(QgsSingleSymbolRenderer(lsym))

    stations = vector_layer(os.path.join(OUTD, "stations_d2h.gpkg"),
                            "GNIP / CNIP station (observed δ²H, ‰)",
                            layer_name="stations")
    graduated_points(stations, "d2h", breaks, RAMP)

    for lyr in (countries, pred, se, provinces, lakes, stations):
        project.addMapLayer(lyr, False)

    # --- extent: Canada bounds with a margin, aspect-matched to the frame
    grid = json.load(open(os.path.join(OUTD, "grid.json")))
    ext = QgsRectangle(grid["xmin"], grid["ymin"], grid["xmax"], grid["ymax"])

    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName("Canada d2H isoscape")
    # initializeDefaults() adds one blank page; remove it so the export
    # has exactly the two pages we build below.
    pc = layout.pageCollection()
    for _ in range(pc.pageCount()):
        pc.deletePage(pc.page(0))

    # =========================================================== page 1
    new_page(layout)
    add_label(layout, 10, 8, 821, 14,
              "Mean annual precipitation δ²H across Canada",
              size=22, bold=True)
    add_label(layout, 10, 23, 821, 7,
              f"An isoscape: a modelled surface of the hydrogen isotope ratio in "
              f"precipitation, from {n_st} GNIP / CNIP stations. Detrended "
              f"interpolation — regression on latitude, elevation, temperature "
              f"and precipitation, then kriging of the residuals. "
              f"Leave-one-out validation R² = {loo['r2']:.2f}, "
              f"RMSE = {loo['rmse_permil']:.2f}‰. "
              f"δ²H and δ¹⁸O track each other on the meteoric water line "
              f"(δ²H ≈ 8·δ¹⁸O + 10); station deuterium excess averages "
              f"+8.0‰.",
              size=9, color=QColor(60, 60, 60))
    map_w, map_h = 560, 480
    m_ext = aspect_rect(ext, map_w / map_h)
    main = add_map(layout, 8, 34, map_w, map_h, m_ext,
                   [stations, provinces, lakes, pred, countries], crs)
    add_grid(main, interval=10.0, font_size=8)
    add_scalebar(layout, main, 18, 496, units_per_seg=500, segments=4)
    add_north(layout, 540, 42)

    # right-hand panel: legend + reading notes
    add_label(layout, 580, 34, 250, 10, "Legend", size=13, bold=True)
    add_label(layout, 580, 46, 250, 7,
              "Mean annual precipitation δ²H (‰, vs VSMOW)", size=9, bold=True)
    ly = legend_rows(layout, 580, 56,
                     [(RAMP[i], f"{breaks[i]:.0f} to {breaks[i + 1]:.0f} ‰")
                      for i in range(len(RAMP))])
    add_ellipse(layout, 581, ly + 4, 5, 5, fill="#fdae61",
                outline="#000000", outline_w=0.4)
    add_label(layout, 595, ly + 3, 235, 7,
              "Station — observed annual mean, same scale", size=9)
    add_rect(layout, 581, ly + 12, 12, 0.5, fill="#666666",
             outline="#666666", outline_w=0.2)
    add_label(layout, 595, ly + 10.5, 235, 7,
              "Province / territory boundary", size=9)
    add_rect(layout, 580, ly + 20, 12, 5.5, fill="#b8d4e8",
             outline="#7fb0d0", outline_w=0.2)
    add_label(layout, 595, ly + 19, 235, 7, "Lake", size=9)
    add_label(layout, 580, 165, 250, 130,
              "How to read this map\n"
              "δ²H is the hydrogen isotope ratio of precipitation, in parts per "
              "thousand (‰) relative to VSMOW. More negative values fall in "
              "the cold north and at altitude; less negative values fall on "
              "the warm Pacific coast and in the south. δ²H is roughly eight "
              "times δ¹⁸O (the meteoric water line), so this map is the "
              "hydrogen companion to the δ¹⁸O isoscape — same stations, same "
              "method, finer relative precision.\n\n"
              "The surface is a model, not a measurement: every grid cell is "
              "predicted from the regression plus the kriged residuals of the "
              "nearest stations. Where stations are sparse — the Arctic "
              "archipelago, northern Québec and Labrador — the prediction "
              "leans on the regression alone; see the uncertainty map "
              "(page 2).\n\n"
              "Stations are coloured by their observed annual mean δ²H on "
              "the same scale as the surface, so a station that disagrees "
              "with the colour under it is visible at a glance.",
              size=9)
    add_label(layout, 580, 310, 250, 80,
              "What it is for\n"
              "Provenance: matching a water, plant, animal or human tissue "
              "sample to where it came from. In archaeology, water isotopes "
              "trace where a person lived and drank; strontium (a separate "
              "isoscape) traces the geology they lived on. Hydrogen is the "
              "more sensitive tracer of the two: its range across Canada is "
              "about eight times the oxygen range.",
              size=9)
    add_label(layout, 580, 400, 250, 80,
              "Coverage\n"
              f"{n_st} stations. CNIP ran 1997–2015 and has ended; there is "
              "no current operational national precipitation-isotope network, "
              "and northern coverage was always patchy — Inuvik and Pond "
              "Inlet have too little data to use, and the far north rests "
              "on five stations. Station years and gaps are listed on "
              "page 2.",
              size=9)
    add_label(layout, 10, 522, 821, 60,
              "Method: precipitation-weighted annual mean δ²H per station; "
              "multiple regression on latitude, elevation, WorldClim 2.1 mean "
              "annual temperature and annual precipitation "
              f"(R² = {reg['r2']:.2f}); ordinary kriging of the residuals "
              f"(exponential variogram: nugget {vario['nugget']:.2f}, sill "
              f"{vario['sill']:.2f}, range {vario['range_m'] / 1000:.0f} km); "
              "10 km grid, EPSG:3347 (NAD83 / Statistics Canada Lambert). "
              "Sources: IAEA/WMO GNIP and the Canadian Network for Isotopes "
              "in Precipitation (CNIP); WorldClim 2.1; Natural Earth. "
              "Made in QGIS 3.34.4 with PyQGIS. δ²H values are per mil (‰) "
              "vs VSMOW. The NOAA Region 7 archive was re-parsed with "
              "corrected fixed-width columns (validated against the "
              "meteoric water line and against the Zenodo GNIP export: "
              "mean difference 0.00‰ on 1,655 overlapping station-months).",
              size=8, color=QColor(60, 60, 60))

    # =========================================================== page 2
    new_page(layout)
    add_label(layout, 10, 8, 821, 14,
              "Uncertainty — and the stations behind the map",
              size=22, bold=True)
    add_label(layout, 10, 23, 821, 7,
              "Kriging standard error of the isoscape (‰). It is smallest "
              "near stations and grows where stations are sparse — the map "
              "shows where the surface is well constrained and where it is "
              "essentially the regression alone.",
              size=9, color=QColor(60, 60, 60))
    # Map on the left, same frame as page 1 (the full Canada extent is
    # nearly square, so a wide short frame would letterbox it badly).
    m2_ext = aspect_rect(ext, 560 / 480)
    m2 = add_map(layout, 8, 32, 560, 480, m2_ext,
                 [stations, provinces, lakes, se, countries], crs)
    add_grid(m2, interval=10.0, font_size=8)
    add_scalebar(layout, m2, 18, 496, units_per_seg=500, segments=4)
    add_north(layout, 540, 42)

    # right-hand panel: legend, station table, validation + gaps
    add_label(layout, 580, 34, 250, 10, "Legend", size=13, bold=True)
    add_label(layout, 580, 46, 250, 7,
              "Kriging standard error (‰)", size=9, bold=True)
    legend_rows(layout, 580, 56,
                [(SE_RAMP[i], f"{se_breaks[i]:.2f} to {se_breaks[i + 1]:.2f} ‰")
                 for i in range(len(se_breaks) - 1)])
    add_ellipse(layout, 581, 100, 5, 5, fill="#fdae61",
                outline="#000000", outline_w=0.4)
    add_label(layout, 595, 99, 235, 7,
              "Station — observed annual mean δ²H", size=9)

    # station table (from the GeoPackage), lightest first, one column
    from osgeo import ogr as _ogr
    ds = _ogr.Open(os.path.join(OUTD, "stations_d2h.gpkg"))
    lyr = ds.GetLayer(0)
    rows = []
    for f in lyr:
        rows.append((f.GetField("station"), f.GetField("source"),
                     f.GetField("years"), f.GetField("n_months"),
                     f.GetField("d2h"), f.GetField("loo_err")))
    rows.sort(key=lambda r: (r[4] is None, r[4]))
    lines = ["Station — years — months — observed δ²H (‰) — LOO error (‰)"]
    for s, src, yrs, nm, v, e in rows:
        short = s.replace(", CANADA", "").replace(", N.W.T.", "").replace(
            " (N.W.T.)", "").replace(" (NEWFOUNDLAND)", " (NL)").replace(
            " (ONTARIO)", " (ON)").replace(" (MANITOBA)", " (MB)").replace(
            " (SASK.)", " (SK)").replace(" (QUEBEC)", " (QC)").replace(
            " (ALBERTA)", " (AB)").replace(" (NOVA SCOTIA)", " (NS)")
        lines.append(f"{short} — {yrs} — {nm} mo — {v:.1f}‰ — {e:+.1f}‰"
                     if v is not None else f"{short} — {yrs} — {nm} mo — no value")
    add_label(layout, 580, 135, 250, 12, "Stations (lightest first)",
              size=11, bold=True)
    # 31 rows at 7pt overflow the 120 mm slot and collide with the
    # Validation block below; 6pt fits (31 lines x ~2.1 mm).
    add_label(layout, 580, 148, 250, 135, "\n".join(lines), size=6)
    add_label(layout, 580, 290, 250, 225,
              "Validation\n"
              "Leave-one-out refits the regression and re-kriges for each "
              "station in turn. "
              f"LOO R² = {loo['r2']:.2f}, RMSE = {loo['rmse_permil']:.2f}‰. "
              "For scale, Delavau et al. (2014) reported RMSE 2.76–2.91‰ "
              "for δ¹⁸O monthly isoscapes — about 22–23‰ in δ²H units — "
              "so this annual δ²H surface validates far better than the "
              "published benchmark, largely because annual means average "
              "out weather noise. The LOO error is still the honest measure "
              "of how well an unmeasured place is predicted.\n\n"
              "Data gaps\n"
              "CNIP ended in 2015; there is no current national "
              "precipitation-isotope network. Coverage was always patchy in "
              "space and time, especially the Arctic archipelago, northern "
              "Québec and Labrador, and the northern interior. WorldClim "
              "2.1 predictors cover 1970–2000 climatology while the isotope "
              "record is 1961–2018: overlapping but not identical periods, "
              "a stated limitation. Eight stations are fully unweighted and "
              "five partly so (the CNIP export carries no precipitation "
              "amounts); on station-years with both, unweighted means run "
              "10.3‰ lighter on average — precipitation weighting matters. "
              "Barrow AK, Inuvik and Pond Inlet were excluded (too few "
              "complete years); Chicago falls just outside the 10 km grid.\n\n"
              "Extrapolation: the lightest values (−240 to −266‰) occur "
              "only on high ground in the far north (Ellesmere Island, up "
              "to 1,853 m in the elevation grid) where no station exists; "
              "the elevation coefficient is calibrated on stations up to "
              "702 m, so treat these as indicative — Agassiz Ice Cap "
              "δ¹⁸O near −30‰ implies δ²H near −230‰. The heaviest value "
              "(−51.7‰) is Sable Island, offshore Nova Scotia, with no "
              "station.\n\n"
              "Independent checks: station deuterium excess averages "
              "+8.0‰ (range −1.0 to +13.1‰), as the meteoric water line "
              "predicts; and the Zenodo GNIP export and the NOAA Region 7 "
              "archive agree to 0.00‰ on 1,655 overlapping station-months, "
              "confirming the corrected parsing of the northern stations.",
              size=9)
    add_label(layout, 10, 522, 821, 60,
              "Sources: IAEA/WMO GNIP; CNIP (Univ. of Victoria / Environment "
              "and Climate Change Canada); WorldClim 2.1 (Fick & Hijmans "
              "2017); Natural Earth (public domain). Method after Bowen & "
              "Wilkinson (2002) and Bowen & Revenaugh (2003). Made in QGIS "
              "3.34.4 with PyQGIS. CRS: EPSG:3347.",
              size=8, color=QColor(60, 60, 60))

    log("exporting PDF…")
    exporter = QgsLayoutExporter(layout)
    settings = QgsLayoutExporter.PdfExportSettings()
    settings.dpi = 150
    settings.forceVectorOutput = True
    settings.appendGeoreference = False
    settings.exportMetadata = False
    if hasattr(settings, "textRenderFormat"):
        settings.textRenderFormat = QgsRenderContext.TextRenderFormat.AlwaysText
        log("text export: AlwaysText (embedded fonts)")
    result = exporter.exportToPdf(OUT, settings)
    log("export result:", result, "(0 = Success)")
    if result != QgsLayoutExporter.Success:
        log("EXPORT FAILED")
        sys.exit(1)
    log(f"wrote {OUT} ({os.path.getsize(OUT) / 1e6:.1f} MB)")
    app.exitQgis()


if __name__ == "__main__":
    main()
