#!/usr/bin/env python3
"""Build the Peterborough land-cover classification map (Piece 2) — PyQGIS, headless.

Page 1 (A3 landscape): Sentinel-2 true colour (left) beside the random-forest
classification (right), same extent; legend with class shares; accuracy summary.
Page 2 (A3 landscape): confusion matrix, class-area bars, method and validation.

Inputs: outputs/peterborough_classification.tif, outputs/peterborough_truecolour.tif,
outputs/classification_metrics.json. CRS: EPSG:32617 (Sentinel-2 native grid),
displayed in NAD83(CSRS) UTM 17N — the same zone. Vector PDF, DejaVu Sans embedded.

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

os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
BASE = os.path.dirname(os.path.abspath(__file__))
OUTDIR = os.path.join(BASE, "outputs")
CLS_TIF = os.path.join(OUTDIR, "peterborough_classification.tif")
RGB_TIF = os.path.join(OUTDIR, "peterborough_truecolour.tif")
METRICS = os.path.join(OUTDIR, "classification_metrics.json")
NORTH_SVG = "/home/hatch/workspace/hydrology-canada/data/north_arrow.svg"
OUT = os.path.join(OUTDIR, "peterborough-landcover.pdf")
FONT = "DejaVu Sans"
MONO = "DejaVu Sans Mono"

PALETTE = {10: ("Tree cover", "#006400"), 20: ("Shrubland", "#ffbb22"),
           30: ("Grassland", "#ffff64"), 40: ("Cropland", "#f096ff"),
           50: ("Built-up", "#fa0000"), 60: ("Bare / sparse vegetation", "#b4b4b4"),
           80: ("Permanent water bodies", "#0064c8"), 90: ("Herbaceous wetland", "#0096a0")}
ABBR = {10: "Tree", 30: "Grass", 40: "Crop", 50: "Built", 60: "Bare",
        80: "Water", 90: "Wetl"}

from qgis.core import (
    QgsApplication, QgsProject, QgsCoordinateReferenceSystem,
    QgsCoordinateTransform, QgsRectangle, QgsVectorLayer, QgsRasterLayer,
    QgsPrintLayout, QgsLayoutItemPage, QgsLayoutItemMap, QgsLayoutItemLabel,
    QgsLayoutItemScaleBar, QgsLayoutItemPicture, QgsLayoutItemShape,
    QgsLayoutPoint, QgsLayoutSize, QgsLayoutExporter, QgsUnitTypes,
    QgsLayoutItemMapGrid, QgsPalettedRasterRenderer, QgsMultiBandColorRenderer,
    QgsFillSymbol, QgsPalLayerSettings, QgsTextFormat, QgsTextBufferSettings,
    QgsRuleBasedLabeling, QgsMemoryProviderUtils, QgsFeature, QgsGeometry,
    QgsPointXY, QgsField, QgsRenderContext,
)
from qgis.PyQt.QtGui import QFont, QColor
from qgis.PyQt.QtCore import Qt, QVariant


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


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


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


PAGE_Y0 = [0.0]


def new_page(layout, width=420, height=297):
    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), family=FONT, absolute=False):
    lab = QgsLayoutItemLabel(layout)
    lab.setText(text)
    lab.setFont(qfont(size, bold, family))
    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):
    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(QColor(240, 240, 240))
    layout.addLayoutItem(m)
    return m


def add_grid(m, interval=0.1, font_size=7):
    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, 130))
    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=5, segments=4):
    bar_w = scalebar_width(m, units_per_seg, segments)
    y = _py(y, False)
    add_rect(layout, x - 4, y - 3, bar_w + 16, 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=14, h=24):
    y = _py(y, False)
    add_rect(layout, x - 4, y - 3, w + 8, h + 14, fill="255,255,255,230",
             outline="#999999", outline_w=0.25, absolute=True)
    nlab = QgsLayoutItemLabel(layout)
    nlab.setText("N")
    nlab.setFont(qfont(13, 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, 10, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(nlab)
    pic = QgsLayoutItemPicture(layout)
    pic.setPicturePath(NORTH_SVG)
    pic.attemptMove(QgsLayoutPoint(x, y + 10, QgsUnitTypes.LayoutMillimeters))
    pic.attemptResize(QgsLayoutSize(w, h, QgsUnitTypes.LayoutMillimeters))
    layout.addLayoutItem(pic)
    return pic


def place_labels():
    """Small named places in the study area, labelled on both maps."""
    lyr = QgsVectorLayer("Point?crs=EPSG:4326", "places", "memory")
    pr = lyr.dataProvider()
    pr.addAttributes([QgsField("name", QVariant.String),
                      QgsField("water", QVariant.Int)])
    lyr.updateFields()
    feats = []
    for lon, lat, name, water in [
            (-78.3197, 44.3091, "Peterborough", 0),
            (-78.30, 44.38, "Otonabee River", 1),
            (-78.365, 44.385, "Chemong Lake", 1),
            (-78.315, 44.295, "Little Lake", 1),
            (-78.22, 44.185, "Rice Lake", 1)]:  # 44.185, not 44.175: the label is clipped at the frame edge otherwise
        f = QgsFeature(lyr.fields())
        f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat)))
        f.setAttributes([name, water])
        feats.append(f)
    pr.addFeatures(feats)
    lyr.updateExtents()
    # rule-based: water names italic blue, places bold black
    def mk(color, italic):
        s = QgsPalLayerSettings()
        s.fieldName = "name"
        fmt = QgsTextFormat()
        fnt = qfont(8, True)
        fnt.setItalic(italic)
        fmt.setFont(fnt)
        fmt.setSize(8)
        fmt.setColor(color)
        buf = QgsTextBufferSettings()
        buf.setEnabled(True)
        buf.setSize(1.0)
        buf.setColor(QColor(255, 255, 255))
        fmt.setBuffer(buf)
        s.setFormat(fmt)
        return s
    root = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
    root.appendChild(QgsRuleBasedLabeling.Rule(mk(QColor(0, 60, 120), True),
                                               0, 0, '"water" = 1', "water", False))
    root.appendChild(QgsRuleBasedLabeling.Rule(mk(QColor(0, 0, 0), False),
                                               0, 0, '"water" = 0', "place", False))
    lyr.setLabeling(QgsRuleBasedLabeling(root))
    lyr.setLabelsEnabled(True)
    return lyr


def main():
    app = init_qgis()
    project = QgsProject.instance()
    crs = QgsCoordinateReferenceSystem("EPSG:32617")
    project.setCrs(crs)
    with open(METRICS) as fh:
        met = json.load(fh)
    oa = met["overall_accuracy"]
    labels = met["labels"]
    areas = met["class_areas"]

    rgb = QgsRasterLayer(RGB_TIF, "Sentinel-2 true colour", "gdal")
    assert rgb.isValid(), "true-colour raster invalid"
    rgb.setRenderer(QgsMultiBandColorRenderer(rgb.dataProvider(), 1, 2, 3))
    cls = QgsRasterLayer(CLS_TIF, "Classification", "gdal")
    assert cls.isValid(), "classification raster invalid"
    classes = []
    for v in labels:
        name, col = PALETTE[v]
        classes.append(QgsPalettedRasterRenderer.Class(v, QColor(col), name))
    cls.setRenderer(QgsPalettedRasterRenderer(cls.dataProvider(), 1, classes))
    places = place_labels()

    ext = cls.extent()
    log("classification extent:", ext.toString(), "size:",
        cls.width(), "x", cls.height())

    layout = QgsPrintLayout(project)
    layout.initializeDefaults()
    layout.setName("Peterborough land cover")
    layout.pageCollection().deletePage(0)  # initializeDefaults adds a blank page

    # ---- page 1: true colour vs classification
    new_page(layout, 420, 297)
    add_label(layout, 12, 8, 396, 14, "Land cover around Peterborough, Ontario",
              size=20, bold=True)
    add_label(layout, 12, 24, 396, 10,
              "Sentinel-2, 15 August 2025 — true colour (left) and random-forest classification (right)",
              size=11, color=QColor(90, 90, 90))
    m1 = add_map(layout, 12, 38, 190, 128, ext, [places, rgb], crs)
    add_grid(m1)
    add_scalebar(layout, m1, 18, 172, units_per_seg=5, segments=4)
    add_north(layout, 182, 44)
    m2 = add_map(layout, 218, 38, 190, 128, ext, [places, cls], crs)
    add_grid(m2)
    add_scalebar(layout, m2, 224, 172, units_per_seg=5, segments=4)
    add_north(layout, 388, 44)
    add_label(layout, 12, 192, 396, 10,
              f"Overall accuracy {oa*100:.1f}% on a held-out validation sample "
              f"({met['n_val']} pixels; {met['n_train']} training pixels). "
              "Labels for training and validation came from ESA WorldCover 2021 — "
              "see page 2 for the confusion matrix and the caveats.",
              size=10, bold=True)
    # legend (right column) + class shares
    lx, ly = 218, 208
    add_label(layout, lx, ly, 190, 10, "Legend — share of the study area", size=11, bold=True)
    for i, v in enumerate(labels):
        name, col = PALETTE[v]
        y = ly + 13 + i * 9
        a = areas[str(v)]
        add_rect(layout, lx, y, 8, 6, fill=col, outline="#3a3a3a", outline_w=0.25)
        add_label(layout, lx + 12, y - 1, 180, 8,
                  f"{name}: {a['km2']:.0f} km² ({a['pct']:.1f}%)", size=9)
    # accuracy summary (left column)
    sx, sy = 12, 208
    add_label(layout, sx, sy, 190, 10, "Validation — per-class F1 score", size=11, bold=True)
    for i, v in enumerate(labels):
        name, _ = PALETTE[v]
        y = sy + 13 + i * 9
        add_label(layout, sx, y - 1, 190, 8,
                  f"{name}: F1 {met['f1'][i]:.2f}  "
                  f"(precision {met['precision'][i]:.2f}, recall {met['recall'][i]:.2f})",
                  size=9)
    add_label(layout, 12, 282, 396, 10,
              "Study area 44.17–44.44°N, 78.55–78.10°W (~36 × 29 km, 1,063 km²). "
              "Projection: NAD83(CSRS) UTM zone 17N (EPSG:32617), Sentinel-2 native grid. "
              "Sources and method on page 2.",
              size=9, color=QColor(90, 90, 90))

    # ---- page 2: method, confusion matrix, class areas
    new_page(layout, 420, 297)
    add_label(layout, 12, 8, 396, 14, "How the classification was made — and how good it is",
              size=20, bold=True)
    # confusion matrix (monospace)
    hdr = "true \\ pred |" + "".join(f"{ABBR[v]:>7}" for v in labels)
    lines = [hdr, "-" * len(hdr)]
    for i, v in enumerate(labels):
        row = met["confusion_matrix"][i]
        lines.append(f"{ABBR[v]:>10} |" + "".join(f"{n:7d}" for n in row))
    cm_text = ("CONFUSION MATRIX — held-out validation pixels (rows = WorldCover label, "
               "columns = predicted)\n" + "\n".join(lines))
    add_label(layout, 12, 28, 200, 90, cm_text, size=8, family=MONO)
    # class-area bars
    bx, by = 232, 28
    add_label(layout, bx, by, 176, 10, "Class areas in the study area", size=11, bold=True)
    max_pct = max(areas[str(v)]["pct"] for v in labels)
    for i, v in enumerate(labels):
        name, col = PALETTE[v]
        a = areas[str(v)]
        y = by + 13 + i * 12
        add_label(layout, bx, y, 70, 8, name, size=9)
        add_rect(layout, bx + 72, y + 1, max(2, 80 * a["pct"] / max_pct), 6,
                 fill=col, outline="#3a3a3a", outline_w=0.25)
        add_label(layout, bx + 156, y, 52, 8, f"{a['km2']:.0f} km²", size=9)
    add_label(layout, 12, 150, 396, 120,
              "METHOD\n"
              "Sensor: Sentinel-2C, Level-2A surface reflectance, four MGRS tiles "
              "(T17TQJ, T17TQK, T17TPJ, T17TPK) mosaicked into one scene, 15 August 2025, "
              "cloud cover 0.001% (Microsoft Planetary Computer STAC). Bands B02, B03, B04, B08 "
              "at 10 m; B11 and B12 at 20 m resampled to 10 m by nearest neighbour. Features: "
              "the six bands plus NDVI (B08−B04)/(B08+B04) and NDWI (B03−B08)/(B03+B08). "
              "Classifier: random forest, 300 trees, scikit-learn 1.9.1. Training and validation "
              "labels were sampled from ESA WorldCover 2021 (10 m), stratified by class: "
              f"{met['n_train']} training pixels and {met['n_val']} validation pixels in total. "
              "Cloud, cloud shadow, cirrus and snow were masked from the Sentinel-2 scene "
              "classification layer (SCL); the scene is effectively cloud-free.\n\n"
              "ACCURACY — READ THIS FIRST\n"
              f"Overall accuracy {oa*100:.1f}% is a random hold-out figure: training and "
              "validation pixels were drawn at random from the same image, so neighbouring "
              "pixels are correlated and the accuracy is an upper estimate versus a spatially "
              "blocked split. The labels themselves are WorldCover 2021, not field survey — "
              "the classifier is being scored against another map, four years older than the "
              "imagery, so real change (new housing, crop rotation) shows up as disagreement "
              "and the true accuracy against the ground is lower. "
              f"{met['worldcover_nodata_pct']:.1f}% of the study area had no "
              "WorldCover label at all; the classification there is extrapolation. "
              "Grassland is the weakest class (F1 0.55), confused most with cropland "
              "(208 of 800 grassland validation pixels predicted as crop); built-up and "
              "bare are confused with each other (135–138 pixels each way).\n\n"
              "Made in QGIS 3.34.4 with AI-assisted Python (PyQGIS) scripting, run headlessly. "
              "Vector PDF; DejaVu Sans embedded; text extractable. Imagery: Copernicus "
              "Sentinel-2 (free and open). Reference labels: ESA WorldCover 2021 (CC BY 4.0).",
              size=10)
    add_label(layout, 12, 282, 396, 10,
              "Sources: Copernicus Sentinel-2 (free and open) · ESA WorldCover 2021 (CC BY 4.0) · "
              "Microsoft Planetary Computer (STAC) · Made in QGIS with PyQGIS",
              size=9, color=QColor(90, 90, 90))

    project.addMapLayer(rgb)
    project.addMapLayer(cls)
    project.addMapLayer(places)
    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()
