#!/usr/bin/env python3
"""Build the Hydrology of Canada map (PyQGIS, headless).

Reads data/hydrology.gpkg and exports a vector PDF to
output/hydrology-canada.pdf:
  p1  main map (A1 landscape, EPSG:3347): drainage regions coloured by
      ocean drainage area, major rivers and lakes, the St. Lawrence River
      from the National Hydro Network, hydrometric stations, legend,
      scale bar, north arrow, graticule
  p2  major river systems table (30 rivers), drainage regions table (25),
      sources, method and caveats

Also saves the QGIS project to output/hydrology-canada.qgz.

Pattern follows ~/workspace/turkiye-sites-map/build_map.py (QGIS 3.34.4,
headless, vector PDF with embedded fonts). Re-runnable:
`MAP_DPI=150 python3 scripts/build_map.py` (default 150 dpi; the map is
fully vector, so dpi only affects raster elements, of which there are none).
"""
import json
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")
GPKG = os.path.join(DATA, "hydrology.gpkg")
OUT_DIR = os.path.join(BASE, "output")
OUT = os.path.join(OUT_DIR, "hydrology-canada.pdf")
PROJECT_OUT = os.path.join(OUT_DIR, "hydrology-canada.qgz")
DPI = int(os.environ.get("MAP_DPI", "150"))
FONT = "DejaVu Sans"
DATE = "2026-11-22"

# ---------------------------------------------------------------- palette
LAND_FILL = "#f0ede6"        # Canada land
LAND_OUTLINE = "#8a8578"
PROV_OUTLINE = "#9a958a"
REGION_OUTLINE = "#7d8894"
LAKE_FILL = "#b9d2e6"
LAKE_OUTLINE = "#5b8ab0"
RIVER_BLUE = "#2f6fb2"
REGION_LABEL = "#6e6a60"
PROV_LABEL = "#4a4640"
OCEAN_LABEL = "#5b7a94"

# drainage regions coloured by ocean drainage area (oda_code)
ODA_FILL = {
    "1": ("#d9e8e4", "Pacific Ocean"),
    "2": ("#dbe7f0", "Arctic Ocean"),
    "3": ("#efe6da", "Gulf of Mexico"),
    "4": ("#e3e3ea", "Hudson Bay"),
    "5": ("#dfe9dc", "Atlantic Ocean"),
}
ODA_EXPR = ("CASE " + " ".join(
    f"WHEN \"oda_code\" = '{k}' THEN '{v[0]}'" for k, v in ODA_FILL.items()) +
    " ELSE '#eeeeee' END")


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


from qgis.core import (
    QgsApplication, QgsProject, QgsCoordinateReferenceSystem,
    QgsCoordinateTransform, QgsRectangle, QgsVectorLayer,
    QgsPrintLayout, QgsLayoutItemPage, QgsLayoutItemMap, QgsLayoutItemLabel,
    QgsLayoutItemScaleBar, QgsLayoutItemPicture, QgsLayoutItemShape,
    QgsLayoutPoint, QgsLayoutSize, QgsLayoutExporter, QgsUnitTypes,
    QgsLayoutItemMapGrid, QgsRuleBasedRenderer, QgsSimpleMarkerSymbolLayer,
    QgsSymbol, QgsProperty, QgsSymbolLayer, QgsWkbTypes,
    QgsRuleBasedLabeling, QgsPalLayerSettings, QgsSimpleLineCallout,
    QgsFillSymbol, QgsLineSymbol, QgsSimpleLineSymbolLayer,
    QgsSingleSymbolRenderer, QgsRenderContext, QgsMarkerLineSymbolLayer,
    QgsSimpleFillSymbolLayer, QgsMarkerSymbol,
    QgsVectorLayerSimpleLabeling, QgsTextFormat, QgsTextBufferSettings,
    QgsPalLayerSettings as Pal, QgsPointXY, Qgis,
)
from qgis.PyQt.QtGui import QFont, QColor
from qgis.PyQt.QtCore import Qt
from osgeo import ogr, osr, gdal


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


# ---------------------------------------------------------------- layout helpers
# (same pattern as turkiye-sites-map/build_map.py: page-relative y)
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()
    log(f"  new page {pc.pageCount()}: y0 = {PAGE_Y0[0]:.1f} mm")
    return page


def _page_y(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), align=Qt.AlignLeft | Qt.AlignTop,
              absolute=False, italic=False):
    y = _page_y(y, absolute)
    lab = QgsLayoutItemLabel(layout)
    lab.setText(text)
    fnt = qfont(size, bold)
    fnt.setItalic(italic)
    lab.setFont(fnt)
    lab.setFontColor(color)
    lab.setHAlign(Qt.AlignLeft if align & Qt.AlignLeft else
                  Qt.AlignHCenter if align & Qt.AlignHCenter else Qt.AlignRight)
    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 = _page_y(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_map(layout, x, y, w, h, extent, layers, crs):
    y = _page_y(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)
    g.setAnnotationFont(qfont(font_size))
    g.setAnnotationFontColor(QColor(40, 40, 40))
    for side in (G.BorderSide.Bottom, G.BorderSide.Left):
        g.setAnnotationDisplay(G.DisplayMode.ShowAll, side)
        g.setAnnotationPosition(G.AnnotationPosition.OutsideMapFrame, side)
    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, right=None):
    bar_w = scalebar_width(m, units_per_seg, segments)
    panel_w = bar_w + 8
    if right is not None:
        x = right - panel_w - 6
    y = _page_y(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 = _page_y(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(DATA, "north_arrow.svg"))
    pic.attemptMove(QgsLayoutPoint(x, y + 12, QgsUnitTypes.LayoutMillimeters))
    pic.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(pic)
    return pic


def map_to_layout(m, lon, lat, project, crs):
    """Layout (mm) position of a WGS84 point inside map item m."""
    xform = QgsCoordinateTransform(
        QgsCoordinateReferenceSystem("EPSG:4326"), crs, project)
    p = xform.transform(lon, lat)
    e = m.extent()
    r = m.rect()
    fx = (p.x() - e.xMinimum()) / e.width()
    fy = 1.0 - (p.y() - e.yMinimum()) / e.height()
    pos = m.positionWithUnits()
    return (pos.x() + fx * r.width(), pos.y() + fy * r.height())


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)


def label_settings(field, size, bold=False, color=QColor(0, 0, 0),
                   italic=False, placement=None, halo=True, halo_size=1.0):
    s = QgsPalLayerSettings()
    s.fieldName = field
    if placement is not None:
        s.placement = placement
    fmt = QgsTextFormat()
    fnt = qfont(size, bold)
    fnt.setItalic(italic)
    fmt.setFont(fnt)
    fmt.setColor(color)
    if halo:
        buf = QgsTextBufferSettings()
        buf.setEnabled(True)
        buf.setSize(halo_size)
        buf.setColor(QColor(255, 255, 255))
        fmt.setBuffer(buf)
    s.setFormat(fmt)
    return s


def flow_arrows(line_symbol, color=RIVER_BLUE, interval_mm=45, size=2.6):
    """Add a marker-line sub-symbol: small triangles pointing downstream
    at regular intervals along the line. The default sub-symbol's marker
    layer is configured IN PLACE: replacing the sub-symbol with a
    createSimple() symbol silently breaks rendering of the whole line
    symbol in QGIS 3.34 (the lines and the arrows both vanish)."""
    ml = QgsMarkerLineSymbolLayer()
    sub = ml.subSymbol()
    layer = sub.symbolLayer(0)
    layer.setShape(QgsSimpleMarkerSymbolLayer.Shape.Triangle)
    layer.setSize(size)
    layer.setColor(QColor(color))
    layer.setStrokeColor(QColor(color))
    layer.setStrokeWidth(0.2)
    layer.setAngle(0)
    try:
        ml.setPlacement(QgsMarkerLineSymbolLayer.Placement.Interval)
    except Exception:
        pass
    try:
        ml.setInterval(interval_mm)
        ml.setIntervalUnit(QgsUnitTypes.RenderMillimeters)
    except Exception:
        pass
    try:
        ml.setRotateMarker(True)
    except Exception:
        pass
    line_symbol.appendSymbolLayer(ml)
    return line_symbol


# ---------------------------------------------------------------- data
def load_tables():
    lengths = json.load(open(os.path.join(DATA, "major_river_lengths.json")))
    ogr.DontUseExceptions()
    ds = ogr.Open(GPKG)
    regions = []
    lyr = ds.GetLayerByName("drainage_regions")
    for f in lyr:
        regions.append({"code": f.GetField("code"), "name": f.GetField("name"),
                        "oda": f.GetField("oda_name"),
                        "area": f.GetField("area_km2")})
    regions.sort(key=lambda r: r["code"])
    counts = {}
    for name in ("stations_active", "stations_discontinued"):
        counts[name] = ds.GetLayerByName(name).GetFeatureCount()
    ds = None
    return lengths, regions, counts


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


def gpkg_layer(name):
    lyr = QgsVectorLayer(f"{GPKG}|layername={name}", name, "ogr")
    assert lyr.isValid(), f"layer {name} failed to load"
    # Guard: in this environment a subset string set on one GPKG layer
    # breaks GDAL's later opens of the same GeoPackage ("unable to open
    # database file"), so a layer can come back with no CRS even though
    # the GeoPackage declares EPSG:4326 for it. The data really are
    # EPSG:4326, so assign it explicitly when QGIS did not read it.
    if not lyr.crs().isValid():
        lyr.setCrs(QgsCoordinateReferenceSystem("EPSG:4326"))
    return lyr


# ---------------------------------------------------------------- page 1
def page_main(layout, project, crs, layers, extent, counts):
    new_page(layout)
    add_label(layout, 12, 8, 700, 14, "Hydrology of Canada",
              size=22, bold=True)
    add_label(layout, 12, 23, 700, 7,
              "Major rivers and lakes, drainage regions and hydrometric stations. "
              f"Compiled {DATE}.",
              size=9, color=QColor(60, 60, 60))
    main = add_map(layout, 30, 38, 610, 538, extent, layers, crs)
    add_grid(main, interval=10.0, font_size=8)
    add_scalebar(layout, main, 42, 556, units_per_seg=500, segments=4)
    add_north(layout, 608, 48)
    # ocean labels (layout labels placed by geography)
    oceans = [
        ("ARCTIC OCEAN", -135.0, 78.0, 11),
        ("BEAUFORT SEA", -139.0, 71.0, 10),
        ("PACIFIC OCEAN", -131.0, 49.0, 11),
        ("HUDSON BAY", -86.0, 58.0, 11),
        ("ATLANTIC OCEAN", -60.0, 44.5, 11),
        ("GULF OF ST. LAWRENCE", -63.0, 49.3, 9),
        ("BAFFIN BAY", -63.0, 72.5, 10),
    ]
    for text, lon, lat, size in oceans:
        lx, ly = map_to_layout(main, lon, lat, project, crs)
        add_label(layout, lx - 30, ly - 4, 90, 8, text, size=size,
                  color=QColor(OCEAN_LABEL), align=Qt.AlignHCenter | Qt.AlignTop,
                  absolute=True)
    # St. Lawrence label, placed along the river below Quebec City
    lx, ly = map_to_layout(main, -69.5, 47.9, project, crs)
    lab = add_label(layout, lx - 40, ly - 4, 110, 8, "St. Lawrence River",
                    size=8.5, color=QColor(RIVER_BLUE), italic=True,
                    align=Qt.AlignHCenter | Qt.AlignTop, absolute=True)
    try:
        lab.setRotation(-18)
    except Exception:
        pass

    # ---- side panel: legend + notes ----
    px, pw = 648, 181
    add_rect(layout, px, 38, pw, 538, fill="#ffffff", outline="#999999",
             outline_w=0.4)
    y = 48
    add_label(layout, px + 8, y, pw - 16, 8, "Legend", size=13, bold=True)
    y += 14
    items = [
        ("fill", LAND_FILL, LAND_OUTLINE, "Land (Canada)"),
        ("fill", ODA_FILL["1"][0], REGION_OUTLINE, "Drains to the Pacific Ocean"),
        ("fill", ODA_FILL["2"][0], REGION_OUTLINE, "Drains to the Arctic Ocean"),
        ("fill", ODA_FILL["4"][0], REGION_OUTLINE, "Drains to Hudson Bay"),
        ("fill", ODA_FILL["5"][0], REGION_OUTLINE, "Drains to the Atlantic Ocean"),
        ("fill", ODA_FILL["3"][0], REGION_OUTLINE, "Drains to the Gulf of Mexico"),
        ("line", REGION_OUTLINE, None, "Drainage region boundary"),
        ("line", PROV_OUTLINE, None, "Province / territory boundary"),
        ("fill", LAKE_FILL, LAKE_OUTLINE, "Lake"),
        ("line", RIVER_BLUE, None, "River"),
        ("line_w", RIVER_BLUE, None, "Major river (flow arrows downstream)"),
        ("fill", LAKE_FILL, LAKE_OUTLINE, "St. Lawrence River (NHN waterbody)"),
        ("dot", "#1f5fa8", None, f"Hydrometric station, active ({counts['active']:,})"),
        ("dot", "#8a8a8a", None, f"Hydrometric station, discontinued ({counts['discontinued']:,})"),
    ]
    for kind, col, outl, text in items:
        if kind == "fill":
            add_rect(layout, px + 10, y + 1, 16, 7, fill=col,
                     outline=outl or "#000000", outline_w=0.4)
        elif kind == "line":
            add_rect(layout, px + 10, y + 3, 16, 1.2, fill=col, outline=col,
                     outline_w=0)
        elif kind == "line_w":
            add_rect(layout, px + 10, y + 2, 16, 2.4, fill=col, outline=col,
                     outline_w=0)
        elif kind == "dot":
            add_label(layout, px + 10, y - 2, 16, 10, "●", size=11,
                      color=QColor(col), align=Qt.AlignHCenter | Qt.AlignTop)
        add_label(layout, px + 30, y, pw - 38, 10, text, size=8.5)
        y += 11
    y += 6
    add_label(layout, px + 8, y, pw - 16, 8, "What the map shows",
              size=11, bold=True)
    y += 12
    notes = [
        "25 drainage regions (Statistics Canada), coloured by the ocean "
        "each drains to.",
        "30 major river systems, labelled; arrows show flow direction "
        "(oriented downstream).",
        "The St. Lawrence River is drawn from the National Hydro Network "
        "(1:50,000) — Natural Earth has only a fragment of it.",
        "Hydrometric stations from Environment and Climate Change Canada "
        "(Water Survey of Canada).",
        "Wetlands are not shown: no clean national wetland layer fits "
        "this scale without cluttering the map.",
    ]
    for n in notes:
        lab = add_label(layout, px + 8, y, pw - 16, 30, "•  " + n, size=8.5)
        y += 30 if len(n) > 110 else 22
    y += 4
    add_label(layout, px + 8, y, pw - 16, 8, "Reading the map",
              size=11, bold=True)
    y += 12
    add_label(layout, px + 8, y, pw - 16, 60,
              "Projection: EPSG:3347 (NAD83 / Statistics Canada Lambert). "
              "Graticule every 10°. Scale bar 500 km divisions. "
              "River lengths are measured on the mapped centrelines in "
              "EPSG:3347 — see the table on page 2.",
              size=8.5)
    # footer
    add_label(layout, 12, 582, 817, 6,
              "Sources: Statistics Canada drainage regions (2017); Natural Earth 10 m rivers and lakes; "
              "National Hydro Network (NHN), GeoBase; Environment and Climate Change Canada hydrometric stations. "
              "All federal data under the Open Government Licence – Canada. See page 2 for full sources and method.",
              size=7.5, color=QColor(60, 60, 60))


# ---------------------------------------------------------------- page 2
def page_table(layout, lengths, regions):
    new_page(layout)
    add_label(layout, 12, 8, 800, 14, "Major river systems of Canada",
              size=20, bold=True)
    add_label(layout, 12, 23, 800, 7,
              "The 30 largest river systems, by mapped length. Lengths are measured on the "
              "mapped centrelines in EPSG:3347 (NAD83 / Statistics Canada Lambert).",
              size=9, color=QColor(60, 60, 60))
    rivers = sorted(lengths.items(),
                    key=lambda kv: kv[1]["length_km"], reverse=True)
    col_x = [12, 428]
    col_w = 401
    y0 = 44
    row_h = 8.5
    for ci in range(2):
        chunk = rivers[ci * 15:(ci + 1) * 15]
        x = col_x[ci]
        add_label(layout, x, y0, 150, 7, "River", size=9, bold=True)
        add_label(layout, x + 155, y0, 45, 7, "Length", size=9, bold=True,
                  align=Qt.AlignRight | Qt.AlignTop)
        add_label(layout, x + 205, y0, col_w - 205, 7, "Outlet",
                  size=9, bold=True)
        add_rect(layout, x, y0 + 7, col_w, 0.4, fill="#000000",
                 outline="#000000", outline_w=0)
        y = y0 + 10
        for name, info in chunk:
            mark = ""
            if info.get("source") == "published":
                mark = " *"
            elif name in ("Hayes", "Koksoak", "Moose", "Ottawa", "Yukon",
                          "Fraser"):
                mark = " †"
            add_label(layout, x, y, 150, 7, name + mark, size=9.5)
            add_label(layout, x + 155, y, 45, 7,
                      f"{info['length_km']:,.0f} km", size=9.5,
                      align=Qt.AlignRight | Qt.AlignTop)
            add_label(layout, x + 205, y, col_w - 205, 7, info["outlet"],
                      size=9.5)
            y += row_h
    y = y0 + 10 + 15 * row_h + 4
    add_label(layout, 12, y, 817, 30,
              "* St. Lawrence: published length, Lake Ontario to the Gulf (1,197 km); the river is drawn "
              "from the National Hydro Network (1:50,000) waterbody and centrelines, not from Natural Earth.\n"
              "† Mapped length is partial: the Natural Earth 10 m centreline is generalised or incomplete for "
              "these rivers (Hayes, Koksoak and Moose are fragments; Ottawa, Yukon and Fraser are shortened by "
              "generalisation). Yukon, Columbia and Red are the Canadian portions only — the centrelines are "
              "clipped at the border.",
              size=8.5, color=QColor(60, 60, 60))

    y2 = y + 34
    add_label(layout, 12, y2, 800, 12, "Drainage regions (Statistics Canada)",
              size=16, bold=True)
    add_label(layout, 12, y2 + 13, 800, 7,
              "25 drainage regions, with the ocean drainage area each flows to and its area.",
              size=9, color=QColor(60, 60, 60))
    y0 = y2 + 26
    for ci in range(2):
        chunk = regions[ci * 13:(ci + 1) * 13]
        x = col_x[ci]
        add_label(layout, x, y0, 30, 7, "Code", size=9, bold=True)
        add_label(layout, x + 32, y0, 175, 7, "Drainage region", size=9,
                  bold=True)
        add_label(layout, x + 210, y0, 100, 7, "Drains to", size=9, bold=True)
        add_label(layout, x + 312, y0, 89, 7, "Area (km²)", size=9, bold=True,
                  align=Qt.AlignRight | Qt.AlignTop)
        add_rect(layout, x, y0 + 7, col_w, 0.4, fill="#000000",
                 outline="#000000", outline_w=0)
        y = y0 + 10
        for r in chunk:
            add_label(layout, x, y, 30, 7, r["code"], size=9.5)
            add_label(layout, x + 32, y, 175, 7, r["name"], size=9.5)
            add_label(layout, x + 210, y, 100, 7, r["oda"], size=9.5)
            add_label(layout, x + 312, y, 89, 7, f"{r['area']:,.0f}",
                      size=9.5, align=Qt.AlignRight | Qt.AlignTop)
            y += 8

    y3 = y0 + 10 + 13 * 8 + 8
    add_label(layout, 12, y3, 800, 12, "Sources, method and caveats",
              size=16, bold=True)
    add_rect(layout, 12, y3 + 13, 817, 62, fill="#f7f5f1",
             outline="#999999", outline_w=0.4)
    src = (
        "Drainage regions — Statistics Canada, Drainage regions of Canada (2017), "
        "https://www150.statcan.gc.ca/n1/en/pub/16-201-x/2017000/sec-1/m-c/m-c-1.1 — "
        "Open Government Licence – Canada. Stored in EPSG:4617 (NAD83(CSRS)), shown in EPSG:3347.\n"
        "Rivers and lakes — Natural Earth 10 m rivers_lake_centerlines and lakes (2021), "
        "public domain; clipped to Canada plus a 0.25° buffer. Centrelines are generalised at "
        "1:10,000,000, so lengths are mapped lengths, not surveyed lengths.\n"
        "St. Lawrence River — National Hydro Network (NHN), GeoBase, Natural Resources Canada, "
        "work units 02MCA00, 0209000, 0210001, 0210002, 0210003 (1:50,000) — Open Government "
        "Licence – Canada. Waterbody polygons plus network centrelines; the unnamed flowlines "
        "between Prescott and Cornwall were selected by corridor. Length in the table is the "
        "published 1,197 km (Lake Ontario to the Gulf).\n"
        "Hydrometric stations — Environment and Climate Change Canada, Water Survey of Canada, "
        "via the MSC GeoMet API (hydrometric-stations collection, retrieved 2026-11-22) — Open "
        "Government Licence – Canada. “Active” = operating at retrieval; “discontinued” = no "
        "longer operating (includes 9 stations with no status recorded).\n"
        "Flow direction — major-river centrelines oriented downstream using elevation (GNIP/CNIP "
        "DEM resampled to EPSG:3347) or, where the DEM gave no clear fall, by mouth position. "
        "NHN centrelines are downstream-oriented in the source. Arrows on the map show flow direction.\n"
        "Provinces and territories — Natural Earth 10 m admin 1. Canada boundary — Natural Earth "
        "10 m admin 0. Map projection EPSG:3347 (NAD83 / Statistics Canada Lambert); data stored "
        "in EPSG:4326 (WGS 84). No wetlands layer is shown: no clean national wetland dataset "
        "fits this scale without cluttering the map."
    )
    add_label(layout, 20, y3 + 18, 801, 140, src, size=8.5)


# ---------------------------------------------------------------- main
def main():
    log("loading tables…")
    lengths, regions, counts = load_tables()
    log(f"rivers in table: {len(lengths)}, drainage regions: {len(regions)}, "
        f"stations active {counts['stations_active']}, "
        f"discontinued {counts['stations_discontinued']}")

    app = init_qgis()
    project = QgsProject.instance()
    crs = QgsCoordinateReferenceSystem("EPSG:3347")
    project.setCrs(crs)
    log(f"QGIS {Qgis.version()}, GDAL {gdal.__version__}, "
        f"PROJ {osr.GetPROJVersionMajor()}.{osr.GetPROJVersionMinor()}")

    # ---- layers (draw order is set per map item, top-first) ----
    canada = gpkg_layer("canada")
    canada.setRenderer(QgsSingleSymbolRenderer(QgsFillSymbol.createSimple(
        {"color": LAND_FILL, "outline_color": LAND_OUTLINE,
         "outline_width": "0.4"})))
    project.addMapLayer(canada)

    regions_lyr = gpkg_layer("drainage_regions")
    regions_lyr.setRenderer(QgsSingleSymbolRenderer(
        QgsFillSymbol.createSimple(
            {"color": "#eeeeee", "outline_color": REGION_OUTLINE,
             "outline_width": "0.5"})))
    # data-defined fill by ocean drainage area (overrides the default above)
    sym = regions_lyr.renderer().symbol()
    sym.symbolLayer(0).setDataDefinedProperty(
        QgsSimpleFillSymbolLayer.PropertyFillColor,
        QgsProperty.fromExpression(ODA_EXPR))
    project.addMapLayer(regions_lyr)
    s = label_settings("name", 7, color=QColor(REGION_LABEL), italic=True,
                       placement=QgsPalLayerSettings.AroundPoint)
    s.dist = 1.0
    regions_lyr.setLabeling(QgsVectorLayerSimpleLabeling(s))
    regions_lyr.setLabelsEnabled(True)

    provinces = gpkg_layer("provinces")
    provinces.setRenderer(QgsSingleSymbolRenderer(
        QgsFillSymbol.createSimple(
            {"color": "255,255,255,0", "outline_color": PROV_OUTLINE,
             "outline_width": "0.35"})))
    project.addMapLayer(provinces)
    s = label_settings("name", 9, bold=True, color=QColor(PROV_LABEL),
                       placement=QgsPalLayerSettings.AroundPoint)
    s.dist = 2.0
    provinces.setLabeling(QgsVectorLayerSimpleLabeling(s))
    provinces.setLabelsEnabled(True)

    lakes = gpkg_layer("lakes")
    lakes.setRenderer(QgsSingleSymbolRenderer(QgsFillSymbol.createSimple(
        {"color": LAKE_FILL, "outline_color": LAKE_OUTLINE,
         "outline_width": "0.4"})))
    project.addMapLayer(lakes)
    big_lakes = ("Lake Superior", "Lake Huron", "Great Bear Lake",
                 "Lake Erie", "Great Slave Lake", "Lake Winnipeg",
                 "Lake Ontario", "Georgian Bay", "Lake Athabasca",
                 "Reindeer Lake", "Lake Winnipegosis", "Nettilling Lake",
                 "Lake Manitoba", "Lake Nipigon", "Lake of the Woods")
    filt = " OR ".join(f"\"name\" = '{n}'" for n in big_lakes)
    s = label_settings("name", 8, color=QColor(RIVER_BLUE), italic=True,
                       placement=QgsPalLayerSettings.AroundPoint)
    s.dist = 1.0
    # NOTE: do NOT use lakes.setSubsetString(filt) here. In this
    # environment a subset string on a GeoPackage layer breaks GDAL's
    # later opens of the same file ("unable to open database file"), so
    # every layer created after it loads with no CRS and renders in the
    # wrong place (major rivers, stations and the St. Lawrence all
    # vanished). Filter the labels instead, with a data-defined Show
    # expression — same 15 lakes, no subset string.
    _props = s.dataDefinedProperties()
    _props.setProperty(QgsPalLayerSettings.Property.Show,
                       QgsProperty.fromExpression(filt))
    s.setDataDefinedProperties(_props)
    lakes.setLabeling(QgsVectorLayerSimpleLabeling(s))
    lakes.setLabelsEnabled(True)
    # a second, unfiltered lakes layer for drawing (labels only on the
    # filtered one would hide the small lakes)
    lakes_all = gpkg_layer("lakes")
    lakes_all.setRenderer(QgsSingleSymbolRenderer(
        QgsFillSymbol.createSimple(
            {"color": LAKE_FILL, "outline_color": LAKE_OUTLINE,
             "outline_width": "0.4"})))
    project.addMapLayer(lakes_all)

    stlaw_water = gpkg_layer("st_lawrence_water")
    stlaw_water.setRenderer(QgsSingleSymbolRenderer(
        QgsFillSymbol.createSimple(
            {"color": LAKE_FILL, "outline_color": LAKE_OUTLINE,
             "outline_width": "0.4"})))
    project.addMapLayer(stlaw_water)

    rivers = gpkg_layer("rivers")
    rivers.setRenderer(QgsSingleSymbolRenderer(QgsLineSymbol.createSimple(
        {"color": RIVER_BLUE, "width": "0.5"})))
    project.addMapLayer(rivers)

    stlaw_lines = gpkg_layer("st_lawrence_nhn")
    stlaw_sym = QgsLineSymbol.createSimple(
        {"color": RIVER_BLUE, "width": "0.5"})
    flow_arrows(stlaw_sym)
    stlaw_lines.setRenderer(QgsSingleSymbolRenderer(stlaw_sym))
    project.addMapLayer(stlaw_lines)

    major = gpkg_layer("major_rivers")
    major_sym = QgsLineSymbol.createSimple(
        {"color": RIVER_BLUE, "width": "0.9"})
    flow_arrows(major_sym)
    major.setRenderer(QgsSingleSymbolRenderer(major_sym))
    project.addMapLayer(major)
    s = label_settings("label", 8.5, color=QColor(RIVER_BLUE), italic=True,
                       placement=QgsPalLayerSettings.Line)
    s.displayAll = False
    major.setLabeling(QgsVectorLayerSimpleLabeling(s))
    major.setLabelsEnabled(True)

    st_act = gpkg_layer("stations_active")
    st_act.setRenderer(QgsSingleSymbolRenderer(QgsMarkerSymbol.createSimple(
        {"name": "circle", "color": "#1f5fa8", "size": "1.8",
         "outline_color": "#ffffff", "outline_width": "0.3"})))
    project.addMapLayer(st_act)

    st_dis = gpkg_layer("stations_discontinued")
    st_dis.setRenderer(QgsSingleSymbolRenderer(QgsMarkerSymbol.createSimple(
        {"name": "circle", "color": "#8a8a8a", "size": "1.1",
         "outline_color": "#ffffff", "outline_width": "0.2"})))
    project.addMapLayer(st_dis)

    # layer stack, top-first: points, labels/rivers, hydro, regions, land
    layers = [st_act, st_dis, major, stlaw_lines, rivers, stlaw_water,
              lakes, lakes_all, provinces, regions_lyr, canada]

    # extent: Canada in EPSG:3347, padded 2%, fitted to the map frame aspect
    ogr.DontUseExceptions()
    ds = ogr.Open(GPKG)
    clyr = ds.GetLayerByName("canada")
    f = next(iter(clyr))
    g = f.GetGeometryRef().Clone()
    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)
    g.Transform(osr.CoordinateTransformation(s4326, s3347))
    env = g.GetEnvelope()
    ds = None
    pad_x = (env[1] - env[0]) * 0.02
    pad_y = (env[3] - env[2]) * 0.02
    rect = QgsRectangle(env[0] - pad_x, env[2] - pad_y,
                        env[1] + pad_x, env[3] + pad_y)
    extent = aspect_rect(rect, 610 / 538)
    log(f"map extent (EPSG:3347): {extent.toString()}")

    counts = {"active": counts["stations_active"],
              "discontinued": counts["stations_discontinued"]}
    log(f"stations: active {counts['active']}, "
        f"discontinued {counts['discontinued']}")

    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    # register the layout with the project so it is saved into the .qgz
    project.layoutManager().addLayout(layout)
    pc = layout.pageCollection()
    while pc.pageCount() > 0:
        pc.deletePage(pc.page(0))

    log("building page 1 (main map)…")
    page_main(layout, project, crs, layers, extent, counts)
    log("building page 2 (tables)…")
    page_table(layout, lengths, regions)

    # save the project for reuse
    os.makedirs(OUT_DIR, exist_ok=True)
    project.write(PROJECT_OUT)
    log(f"wrote project {PROJECT_OUT}")

    total = layout.pageCollection().pageCount()
    log(f"total pages: {total}; exporting at {DPI} dpi…")
    exporter = QgsLayoutExporter(layout)
    settings = QgsLayoutExporter.PdfExportSettings()
    settings.dpi = DPI
    settings.forceVectorOutput = True
    settings.appendGeoreference = False
    settings.exportMetadata = False
    if hasattr(settings, "textRenderFormat"):
        settings.textRenderFormat = QgsRenderContext.TextRenderFormat.AlwaysText
        log("text export: AlwaysText (embedded fonts)")
    else:
        log("WARNING: PdfExportSettings has no textRenderFormat — "
            "text will export as outlines")
    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()
