#!/usr/bin/env python3
"""Piece 2: Sentinel-2 land-cover classification, Peterborough, Ontario.

Scene: Sentinel-2C L2A, 2025-08-15, tile T17TQJ, cloud 0.001% (Planetary
Computer STAC). Bands B02 B03 B04 B08 (10 m) + B11 B12 (20 m resampled 10 m),
features = 6 bands + NDVI + NDWI. Supervised random forest (scikit-learn,
300 trees). Training/validation labels sampled from ESA WorldCover 2021
(10 m), stratified random split (seed 42): up to 1,500 training + 800
validation pixels per class. Caveat stated on the map: a random hold-out
overstates accuracy versus a spatially blocked split, because neighbouring
pixels are correlated; the reported accuracy is therefore an upper estimate.
Mask: SCL cloud / shadow / cirrus / snow excluded (scene is ~0% cloud).
Outputs: classification GeoTIFF (EPSG:32617) + true-colour RGB GeoTIFF.
"""
import os, sys
import numpy as np
from osgeo import gdal
gdal.DontUseExceptions()

BASE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(BASE, "data", "peterborough")
OUT = os.path.join(BASE, "outputs")
os.makedirs(OUT, exist_ok=True)

def read(path):
    ds = gdal.Open(path)
    a = ds.GetRasterBand(1).ReadAsArray()
    gt, prj = ds.GetGeoTransform(), ds.GetProjection()
    ds = None
    return a, gt, prj

bands = {}
for b in ["b02", "b03", "b04", "b08", "b11", "b12"]:
    bands[b], gt, prj = read(os.path.join(DATA, f"s2_20250815_{b}.tif"))
    print(b, bands[b].shape, bands[b].dtype, "min/max:", bands[b].min(), bands[b].max())
scl, _, _ = read(os.path.join(DATA, "s2_20250815_scl.tif"))
wc, _, _ = read(os.path.join(DATA, "worldcover_2021.tif"))
print("scl unique:", np.unique(scl, return_counts=True))
print("worldcover unique:", np.unique(wc, return_counts=True))

h, w = wc.shape
# class map: WorldCover value -> (code, label)
CLASSES = {10: "Tree cover", 20: "Shrubland", 30: "Grassland", 40: "Cropland",
           50: "Built-up", 60: "Bare / sparse vegetation", 80: "Permanent water bodies",
           90: "Herbaceous wetland"}
mask_bad_scl = np.isin(scl, [0, 3, 8, 9, 10, 11])  # nodata, shadow, cloud, cirrus, snow/ice
# safety net: pixels where every band reads 0 are outside the tile coverage
all_zero = (bands["b02"] == 0) & (bands["b04"] == 0) & (bands["b08"] == 0)
valid = (~mask_bad_scl) & (~all_zero) & np.isin(wc, list(CLASSES))
print("valid pixels:", int(valid.sum()), "of", h * w, f"({valid.mean()*100:.1f}%)")

rng = np.random.default_rng(42)
train_idx, val_idx = [], []
for v, label in CLASSES.items():
    ys, xs = np.where(valid & (wc == v))
    n = len(ys)
    print(f"  {label}: {n} px ({n/(h*w)*100:.1f}%)")
    if n < 200:
        print(f"    -> too few, class dropped from training")
        continue
    perm = rng.permutation(n)
    n_tr = min(1500, n // 2)
    n_va = min(800, n - n_tr)
    train_idx.append((ys[perm[:n_tr]], xs[perm[:n_tr]], np.full(n_tr, v)))
    val_idx.append((ys[perm[n_tr:n_tr + n_va]], xs[perm[n_tr:n_tr + n_va]], np.full(n_va, v)))

def feats_at(ys, xs):
    b02 = bands["b02"][ys, xs].astype(np.float32)
    b03 = bands["b03"][ys, xs].astype(np.float32)
    b04 = bands["b04"][ys, xs].astype(np.float32)
    b08 = bands["b08"][ys, xs].astype(np.float32)
    b11 = bands["b11"][ys, xs].astype(np.float32)
    b12 = bands["b12"][ys, xs].astype(np.float32)
    ndvi = (b08 - b04) / np.maximum(b08 + b04, 1.0)
    ndwi = (b03 - b08) / np.maximum(b03 + b08, 1.0)
    return np.column_stack([b02, b03, b04, b08, b11, b12, ndvi, ndwi])

Xtr = np.vstack([feats_at(y, x) for y, x, _ in train_idx])
ytr = np.concatenate([v for _, _, v in train_idx])
Xva = np.vstack([feats_at(y, x) for y, x, _ in val_idx])
yva = np.concatenate([v for _, _, v in val_idx])
print("train:", Xtr.shape, "validation:", Xva.shape)

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
clf = RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=42,
                             class_weight="balanced_subsample")
clf.fit(Xtr, ytr)
pred_va = clf.predict(Xva)
print("OVERALL ACCURACY (random hold-out):", round(accuracy_score(yva, pred_va), 4))
labels = sorted(set(yva.tolist()))
print(classification_report(yva, pred_va, labels=labels,
                            target_names=[CLASSES[v] for v in labels], digits=3))
cm = confusion_matrix(yva, pred_va, labels=labels)
print("confusion matrix rows=true, cols=pred, labels:", labels)
print(cm)
importances = clf.feature_importances_
print("feature importances (B02 B03 B04 B08 B11 B12 NDVI NDWI):",
      [round(float(x), 3) for x in importances])
from sklearn.metrics import precision_recall_fscore_support
prec, rec, f1, sup = precision_recall_fscore_support(yva, pred_va, labels=labels, zero_division=0)
import json as _json
metrics = {
    "overall_accuracy": float(accuracy_score(yva, pred_va)),
    "n_train": int(len(ytr)), "n_val": int(len(yva)),
    "labels": labels,
    "label_names": [CLASSES[v] for v in labels],
    "confusion_matrix": cm.tolist(),
    "precision": [float(x) for x in prec],
    "recall": [float(x) for x in rec],
    "f1": [float(x) for x in f1],
    "support": [int(x) for x in sup],
    "feature_importances": [float(x) for x in importances],
}
with open(os.path.join(OUT, "classification_metrics.json"), "w") as fh:
    _json.dump(metrics, fh, indent=2)
print("wrote", os.path.join(OUT, "classification_metrics.json"))

# predict the full AOI in row blocks
class_out = np.zeros((h, w), dtype=np.uint8)
BLOCK = 400
for r0 in range(0, h, BLOCK):
    r1 = min(h, r0 + BLOCK)
    sl = slice(r0, r1)
    b02 = bands["b02"][sl].astype(np.float32); b03 = bands["b03"][sl].astype(np.float32)
    b04 = bands["b04"][sl].astype(np.float32); b08 = bands["b08"][sl].astype(np.float32)
    b11 = bands["b11"][sl].astype(np.float32); b12 = bands["b12"][sl].astype(np.float32)
    ndvi = (b08 - b04) / np.maximum(b08 + b04, 1.0)
    ndwi = (b03 - b08) / np.maximum(b03 + b08, 1.0)
    X = np.column_stack([b02.ravel(), b03.ravel(), b04.ravel(), b08.ravel(),
                         b11.ravel(), b12.ravel(), ndvi.ravel(), ndwi.ravel()])
    pred = clf.predict(X).reshape(r1 - r0, w)
    class_out[sl] = np.where(mask_bad_scl[sl] | all_zero[sl], 0, pred).astype(np.uint8)
    print(f"predicted rows {r0}-{r1}")
    del X, pred

# class areas
class_areas = {}
for v, label in CLASSES.items():
    n = int((class_out == v).sum())
    class_areas[v] = {"name": label, "pixels": n, "km2": n * 100 / 1e6,
                      "pct": n / (h * w) * 100}
    print(f"  classified {label}: {n} px = {n*100/1e6:.1f} km2 ({n/(h*w)*100:.1f}%)")
print("  masked (cloud/shadow):", int((class_out == 0).sum()), "px")
with open(os.path.join(OUT, "classification_metrics.json")) as fh:
    metrics = _json.load(fh)
metrics["class_areas"] = {str(k): v for k, v in class_areas.items()}
metrics["masked_pixels"] = int((class_out == 0).sum())
metrics["aoi_km2"] = h * w * 100 / 1e6
metrics["worldcover_nodata_pct"] = float((wc == 0).mean() * 100)
with open(os.path.join(OUT, "classification_metrics.json"), "w") as fh:
    _json.dump(metrics, fh, indent=2)

drv = gdal.GetDriverByName("GTiff")
ds = drv.Create(os.path.join(OUT, "peterborough_classification.tif"), w, h, 1, gdal.GDT_Byte,
                ["COMPRESS=LZW", "TILED=YES"])
ds.SetGeoTransform(gt); ds.SetProjection(prj)
ds.GetRasterBand(1).WriteArray(class_out)
ds.GetRasterBand(1).SetNoDataValue(0)
# WorldCover palette so the file reads sensibly in any GIS
PALETTE = {10: (0, 100, 0), 20: (255, 187, 34), 30: (255, 255, 100), 40: (240, 150, 255),
           50: (250, 0, 0), 60: (180, 180, 180), 80: (0, 100, 200), 90: (0, 150, 160)}
ct = gdal.ColorTable()
for v, rgb in PALETTE.items():
    ct.SetColorEntry(v, rgb + (255,))
ds.GetRasterBand(1).SetColorTable(ct)
ds = None

# true-colour RGB (2-98 percentile stretch, 8-bit) for the map backdrop
def stretch(a):
    lo, hi = np.percentile(a[a > 0], [2, 98])
    return np.clip((a.astype(np.float32) - lo) / (hi - lo) * 255, 0, 255).astype(np.uint8)
rgb = np.stack([stretch(bands["b04"]), stretch(bands["b03"]), stretch(bands["b02"])])
ds = drv.Create(os.path.join(OUT, "peterborough_truecolour.tif"), w, h, 3, gdal.GDT_Byte,
                ["COMPRESS=LZW", "TILED=YES", "PHOTOMETRIC=RGB"])
ds.SetGeoTransform(gt); ds.SetProjection(prj)
for i in range(3):
    ds.GetRasterBand(i + 1).WriteArray(rgb[i])
ds = None
print("wrote classification + true-colour GeoTIFFs")
