"""Extract a 400 m terrain window; no flow model or surveyed boundary.

Run with Python, rasterio, pyproj, numpy and matplotlib installed:
  python extract-terrain.py OUTPUT_DIRECTORY
The remote Cloud Optimized GeoTIFF is read by window, never downloaded whole.
"""
import hashlib
import json
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import matplotlib
import pyproj
import rasterio
from pyproj import Transformer
from rasterio.windows import Window, bounds

OUT = Path(sys.argv[1])
OUT.mkdir(parents=True, exist_ok=True)
ITEM = "https://stac.gisdata.mn.gov/collections/minnesota-100km-sections-DEM-0.5m/items/dem_5_51_m"
LON, LAT = -92.0899378, 46.807297
with urllib.request.urlopen(ITEM, timeout=30) as response:
    raw = response.read()
(OUT / "source-item.json").write_bytes(raw)
item = json.loads(raw)
asset = item["assets"]["data"]["href"]
with rasterio.Env(GDAL_DISABLE_READDIR_ON_OPEN="EMPTY_DIR", GDAL_HTTP_TIMEOUT=30,
                  CPL_VSIL_CURL_ALLOWED_EXTENSIONS=".tif"):
    with rasterio.open(asset) as source:
        x, y = Transformer.from_crs(4326, source.crs, always_xy=True).transform(LON, LAT)
        row, col = source.index(x, y)
        assert source.res == (0.5, 0.5), source.res
        assert 400 <= row < source.height - 400 and 400 <= col < source.width - 400
        window = Window(col - 400, row - 400, 800, 800)
        terrain = source.read(1, window=window, masked=True)
        assert terrain.count() > 0, "No usable terrain in this window"
        transform = source.window_transform(window)
        extent = bounds(window, source.transform)
        profile = source.profile.copy()
        profile.update(driver="GTiff", width=800, height=800, transform=transform,
                       compress="deflate", tiled=True, blockxsize=256, blockysize=256)
        with rasterio.open(OUT / "terrain.tif", "w", **profile) as target:
            target.write(terrain.filled(source.nodata), 1)
        metadata = {
            "retrieved_at": datetime.now(timezone.utc).isoformat(),
            "source_item": ITEM, "source_asset": asset,
            "source_title": item["properties"]["fgdc:title"],
            "source_published_metadata": item["properties"]["fgdc:published"],
            "source_item_sha256": hashlib.sha256(raw).hexdigest(),
            "terrain_sha256": hashlib.sha256((OUT / "terrain.tif").read_bytes()).hexdigest(),
            "horizontal_crs": source.crs.to_string(),
            "vertical_datum_as_reported_by_source": "NAVD88 (Geoid09)",
            "vertical_unit": "metres",
            "marker_wgs84": [LON, LAT], "marker_projected": [x, y],
            "window": {"row": row - 400, "column": col - 400, "height": 800, "width": 800},
            "bounds": list(extent), "grid_metres": [0.5, 0.5],
            "valid_pixels": int(terrain.count()), "nodata_pixels": int(terrain.size - terrain.count()),
            "elevation_range_metres": [float(terrain.min()), float(terrain.max())],
            "interpretation": "Terrain only. Unsurveyed garden-program marker; no garden boundary, contributing area, pipe network, flow model, runoff volume, field review or intervention permission.",
            "limitations_and_redistribution": "https://www.mngeo.state.mn.us/chouse/disclaimer.html",
            "software": {"python": sys.version.split()[0], "rasterio": rasterio.__version__,
                         "numpy": np.__version__, "pyproj": pyproj.__version__,
                         "matplotlib": matplotlib.__version__},
        }
(OUT / "extraction.json").write_text(json.dumps(metadata, indent=2) + "\n")
print(json.dumps(metadata), flush=True)

matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 8.5))
left, bottom, right, top = extent
shown = ax.imshow(terrain, origin="upper", cmap="terrain",
                  extent=[left - x, right - x, bottom - y, top - y])
ax.plot(0, 0, marker="x", color="black", markersize=10, markeredgewidth=2)
ax.annotate("Garden-program marker\nBoundary unverified", (0, 0), xytext=(12, 12),
            textcoords="offset points", fontsize=9,
            bbox={"facecolor": "white", "alpha": 0.85, "edgecolor": "none"})
ax.set(xlabel="Easting from marker (metres)", ylabel="Northing from marker (metres)",
       title="Terrain around Chester Creek Community Garden\n400 m window · 0.5 m grid")
fig.colorbar(shown, ax=ax, shrink=0.8, label="Elevation (metres; source reports NAVD88)")
fig.text(0.5, 0.035, "Source: MnGeo / Minnesota DNR, Statewide Seamless 0.5m Lidar DEM, 2025\n"
         "Terrain extract: 2026-10-04. No drainage model, surveyed boundary or site review.",
         ha="center", fontsize=8)
fig.tight_layout(rect=[0, 0.08, 1, 1])
fig.savefig(OUT / "terrain.png", dpi=180)
