#!/usr/bin/env python3
"""Build the Ontario protected-areas map (Piece 1) — PyQGIS, headless.

Page 1 (A1 portrait): Ontario's provincial parks (347, by class) and
conservation reserves (306), with conservation-authority boundaries,
Great Lakes, and the Ontario boundary. EPSG:3161 (NAD83 / Ontario MNR Lambert).
Page 2 (A1 portrait): southern Ontario detail (all 36 conservation
authorities + southern parks) with method, validation and sources.

Data: outputs/ontario_protected_areas.gpkg (GeoHub LIO Open Data, OGL-Ontario).
Vector PDF, DejaVu Sans embedded, text extractable.

QGIS 3.34.4, Ubuntu noble. Run with the system python3.
"""
import os, sys

os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
BASE = os.path.dirname(os.path.abspath(__file__))
GPKG = os.path.join(BASE, "outputs", "ontario_protected_areas.gpkg")
NORTH_SVG = "/home/hatch/workspace/hydrology-canada/data/north_arrow.svg"
OUT = os.path.join(BASE, "outputs", "ontario-protected-areas.pdf")
FONT = "DejaVu Sans"

from qgis.core import (
    QgsApplication, QgsProject, QgsCoordinateReferenceSystem,
    QgsCoordinateTransform, QgsRectangle, QgsVectorLayer,
    QgsPrintLayout, QgsLayoutItemPage, QgsLayoutItemMap, QgsLayoutItemLabel,
    QgsLayoutItemScaleBar, QgsLayoutItemPicture, QgsLayoutItemShape,
    QgsLayoutPoint, QgsLayoutSize, QgsLayoutExporter, QgsUnitTypes,
    QgsLayoutItemMapGrid, QgsCategorizedSymbolRenderer, QgsRendererCategory,
    QgsSymbol, QgsSingleSymbolRenderer, QgsFillSymbol, QgsLineSymbol,
    QgsPalLayerSettings, QgsTextFormat,
    QgsTextBufferSettings, QgsRuleBasedLabeling, QgsRenderContext,
)
from qgis.PyQt.QtGui import QFont, QColor
from qgis.PyQt.QtCore import Qt


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=594, height=841):
    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 _py(y, absolute=False):
    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):
    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, _py(y, absolute), 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):
    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, _py(y, absolute), 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, bg=QColor(238, 240, 234)):
    m = QgsLayoutItemMap(layout)
    m.attemptMove(QgsLayoutPoint(x, _py(y, False), QgsUnitTypes.LayoutMillimeters))
    m.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    m.setExtent(extent)
    m.setCrs(crs)
    m.setLayers(layers)
    m.setBackgroundColor(bg)
    layout.addLayoutItem(m)
    return m


def add_grid(m, interval=5.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(120, 120, 120, 90))
    g.setGridLineWidth(0.25)
    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=100, 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(NORTH_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):
    """Expand a QgsRectangle (projected metres) to the given w/h 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 lonlat_rect(lonmin, latmin, lonmax, latmax, crs, project):
    xform = QgsCoordinateTransform(
        QgsCoordinateReferenceSystem("EPSG:4326"), crs, project)
    return xform.transformBoundingBox(QgsRectangle(lonmin, latmin, lonmax, latmax))


# ---------------------------------------------------------------- layers
def vec_layer(name):
    lyr = QgsVectorLayer(f"{GPKG}|layername={name}", name, "ogr")
    assert lyr.isValid(), f"layer {name} invalid"
    return lyr


def simple_fill(layer, color, outline="#4a4a4a", outline_w=0.25):
    layer.setRenderer(QgsSingleSymbolRenderer(QgsFillSymbol.createSimple(
        {"color": color, "outline_color": outline, "outline_width": str(outline_w)})))


def simple_line(layer, color, width=0.6, style="solid"):
    layer.setRenderer(QgsSingleSymbolRenderer(QgsLineSymbol.createSimple(
        {"color": color, "width": str(width), "line_style": style})))


PARK_CLASSES = [
    ("Nature Reserve", "#2e7d32"),
    ("Natural Environment", "#66bb6a"),
    ("Waterway", "#4dd0e1"),
    ("Recreational", "#ffb300"),
    ("Wilderness", "#6a1b9a"),
    ("Cultural Heritage", "#8d6e63"),
    ("Other", "#9e9e9e"),
]
CLASS_EXPR = ("CASE WHEN \"PROVINCIAL_PARK_CLASS_ENG\" IN ('Urban','Adventure','Unclassified') "
              "THEN 'Other' ELSE \"PROVINCIAL_PARK_CLASS_ENG\" END")


def style_parks(layer):
    cats = []
    for name, color in PARK_CLASSES:
        sym = QgsFillSymbol.createSimple(
            {"color": color, "outline_color": "#3a3a3a", "outline_width": "0.25"})
        cats.append(QgsRendererCategory(name, sym, name))
    layer.setRenderer(QgsCategorizedSymbolRenderer(CLASS_EXPR, cats))


def label_rule(layer, field, expression, size, color=QColor(0, 0, 0), is_expression=False):
    """Rule-based labelling: only features matching the expression are labelled.
    If is_expression, `field` is a QGIS expression, not a field name."""
    s = QgsPalLayerSettings()
    s.fieldName = field
    s.isExpression = is_expression
    fmt = QgsTextFormat()
    fmt.setFont(qfont(size, True))
    fmt.setSize(size)
    fmt.setColor(color)
    buf = QgsTextBufferSettings()
    buf.setEnabled(True)
    buf.setSize(1.0)
    buf.setColor(QColor(255, 255, 255))
    fmt.setBuffer(buf)
    s.setFormat(fmt)
    rule = QgsRuleBasedLabeling.Rule(s, 0, 0, expression, "filtered", False)
    root = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
    root.appendChild(rule)
    layer.setLabeling(QgsRuleBasedLabeling(root))
    layer.setLabelsEnabled(True)


def main():
    app = init_qgis()
    project = QgsProject.instance()
    crs = QgsCoordinateReferenceSystem("EPSG:3161")
    project.setCrs(crs)

    boundary = vec_layer("ontario_boundary")
    parks = vec_layer("provincial_parks")
    reserves = vec_layer("conservation_reserves")
    cas = vec_layer("conservation_authorities")
    cas_lab = vec_layer("conservation_authorities")  # labelled clone, page 2 only
    lakes = vec_layer("great_lakes")

    simple_fill(boundary, "#fbfaf3", outline="#1a1a1a", outline_w=0.7)
    style_parks(parks)
    simple_fill(reserves, "#00897b", outline="#3a3a3a", outline_w=0.25)
    simple_line(cas, "#5d4037", width=0.7, style="dash")
    simple_line(cas_lab, "#5d4037", width=0.7, style="dash")
    simple_fill(lakes, "#a8d0e6", outline="#7fb3d5", outline_w=0.25)

    # labels: only the largest parks (REGULATED_AREA is hectares; >= 300,000 ha
    # = 3,000 km2), so the province map is not crowded with tiny-park names.
    # The names carry a class suffix in the data ("... (WILDERNESS CLASS)");
    # strip it for the label.
    strip_suffix = ("CASE WHEN strpos(\"PROTECTED_AREA_NAME_ENG\", ' (') > 0 "
                    "THEN left(\"PROTECTED_AREA_NAME_ENG\", "
                    "strpos(\"PROTECTED_AREA_NAME_ENG\", ' (') - 1) "
                    "ELSE \"PROTECTED_AREA_NAME_ENG\" END")
    label_rule(parks, strip_suffix, '"REGULATED_AREA" >= 300000', 9,
               is_expression=True)
    # conservation-authority names only on the page-2 detail map
    label_rule(cas_lab, "COMMON_NAME", "TRUE", 8, color=QColor(93, 64, 55))

    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName("Ontario protected areas")
    layout.pageCollection().deletePage(0)  # initializeDefaults adds a blank page

    # ---- page 1: province map, A1 portrait
    new_page(layout, 594, 841)
    add_label(layout, 20, 18, 554, 16, "Ontario's protected areas", size=24, bold=True)
    add_label(layout, 20, 40, 554, 12,
              "Provincial parks and conservation reserves — Land Information Ontario open data",
              size=12, color=QColor(90, 90, 90))
    full = QgsRectangle(196507, 11675002, 1763302, 13367504)
    frame = aspect_rect(full, 554 / 600)
    m = add_map(layout, 20, 58, 554, 600, frame,
                [parks, reserves, cas, lakes, boundary], crs)
    add_grid(m, interval=5.0)
    add_scalebar(layout, m, 30, 630, units_per_seg=100, segments=4)
    add_north(layout, 540, 70)
    add_label(layout, 20, 664, 554, 40,
              "347 provincial parks (82,906 km², 7.7% of Ontario's land) and 306 conservation "
              "reserves (15,281 km², 1.4%), under the Provincial Parks and Conservation "
              "Reserves Act, 2006. Dashed outlines are the 36 conservation-authority areas. "
              "Projection: NAD83 / Ontario MNR Lambert (EPSG:3161). Sources and method on page 2.",
              size=10)
    # legend
    lx, ly = 20, 712
    add_label(layout, lx, ly, 200, 10, "Legend", size=11, bold=True)
    leg = [("Provincial park — Nature Reserve", "#2e7d32"),
           ("Provincial park — Natural Environment", "#66bb6a"),
           ("Provincial park — Waterway", "#4dd0e1"),
           ("Provincial park — Recreational", "#ffb300"),
           ("Provincial park — Wilderness", "#6a1b9a"),
           ("Provincial park — Cultural Heritage", "#8d6e63"),
           ("Provincial park — Other (Urban, Adventure, Unclassified)", "#9e9e9e"),
           ("Conservation reserve", "#00897b"),
           ("Great Lakes and large lakes", "#a8d0e6")]
    for i, (txt, col) in enumerate(leg):
        y = ly + 14 + i * 9
        add_rect(layout, lx, y, 8, 6, fill=col, outline="#3a3a3a", outline_w=0.25)
        add_label(layout, lx + 12, y - 1, 300, 8, txt, size=9)
    add_label(layout, 330, ly + 14, 244, 90,
              "Conservation-authority areas are shown as dashed outlines only; "
              "they are administrative areas, not protected land.\n\n"
              "Park class is the regulated class under the Provincial Parks "
              "and Conservation Reserves Act, 2006. Areas are the regulated "
              "areas published with the data (hectares), not planimetered "
              "from this map.",
              size=9)

    # ---- page 2: southern Ontario detail + method
    new_page(layout, 594, 841)
    add_label(layout, 20, 18, 554, 16, "Southern Ontario — detail", size=24, bold=True)
    add_label(layout, 20, 40, 554, 12,
              "The south holds all 36 conservation authorities and most of the small parks",
              size=12, color=QColor(90, 90, 90))
    s_ext = lonlat_rect(-81.6, 41.6, -74.2, 45.6, crs, project)
    s_frame = aspect_rect(s_ext, 554 / 330)
    m2 = add_map(layout, 20, 58, 554, 330, s_frame,
                 [parks, reserves, cas_lab, lakes, boundary], crs)
    add_grid(m2, interval=1.0)
    add_scalebar(layout, m2, 30, 360, units_per_seg=50, segments=4)
    add_north(layout, 540, 70)
    add_label(layout, 20, 400, 554, 220,
              "HOW THIS MAP WAS MADE\n"
              "Data: Provincial Park Regulated (347 features) and Conservation Reserve Regulated "
              "(306 features), Land Information Ontario Open Data (LIO_Open03), via the Ontario "
              "GeoHub ArcGIS REST services; Conservation Authority Administrative Areas (36 "
              "features), same source. All under the Open Government Licence – Ontario. "
              "Ontario boundary from Natural Earth admin-1; lakes from Natural Earth 10 m lakes.\n\n"
              "Projection: NAD83 / Ontario MNR Lambert (EPSG:3161), the Ontario ministry "
              "provincial projection. Source data are published in NAD83; the ~1–2 m offset to "
              "NAD83(CSRS) is irrelevant at this scale and is stated, not hidden. "
              "Geometries were validated (8 self-intersecting rings repaired with MakeValid), "
              "reprojected, and simplified to 100 m for province-scale display — the 1 ha Kama "
              "Hills park was kept whole. Counts reconcile exactly with the services "
              "(347 / 306 / 36).\n\n"
              "Areas: regulated areas as published (parks 82,906 km² = 7.70% of Ontario's "
              "1,076,395 km² land area; reserves 15,281 km² = 1.42%; together 98,187 km² = "
              "9.12%). Planimetered geometry areas differ by 0.9% (parks) and 2.1% (reserves), "
              "which is the 100 m simplification; the published regulated areas are the "
              "authoritative figures. Conservation-authority areas (108,598 km²) overlap the "
              "parks and are administrative, not protected land, so they are not added to the "
              "total.\n\n"
              "Made in QGIS 3.34.4 with AI-assisted Python (PyQGIS) scripting, run headlessly. "
              "Vector PDF; DejaVu Sans embedded; text extractable.",
              size=10)
    add_label(layout, 20, 800, 554, 12,
              "Sources: Ontario GeoHub / Land Information Ontario (Open Government Licence – "
              "Ontario) · Natural Earth (public domain) · Made in QGIS with PyQGIS",
              size=9, color=QColor(90, 90, 90))

    project.addMapLayer(boundary)
    project.addMapLayer(parks)
    project.addMapLayer(reserves)
    project.addMapLayer(cas)
    project.addMapLayer(cas_lab)
    project.addMapLayer(lakes)
    project.layoutManager().addLayout(layout)

    settings = QgsLayoutExporter.PdfExportSettings()
    settings.dpi = 150
    settings.forceVectorOutput = True
    # Text as embedded-font text objects, NOT glyph outlines (Türkiye pattern).
    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")
    exporter = QgsLayoutExporter(layout)
    res = exporter.exportToPdf(OUT, settings)
    log("export result:", res)
    log("wrote", OUT, os.path.getsize(OUT) // 1024, "KB")
    app.exitQgis()


if __name__ == "__main__":
    main()
