#!/usr/bin/env python3
"""Prep Piece 1 data into a GeoPackage in EPSG:3161 (NAD83 / Ontario MNR Lambert).

Inputs: GeoHub GeoJSONs (EPSG:4326), Ontario boundary, Natural Earth 10m lakes.
Steps: MakeValid (8 source geometries self-intersect), reproject to 3161,
simplify to 100 m for province-scale display (stated on the map), clip lakes
to the Ontario neighbourhood. Prints area reconciliation stats.
Ontario land area (StatCan): 1,076,395 km2.
"""
import json, os, sys

from osgeo import ogr, osr
ogr.DontUseExceptions()

BASE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(BASE, "data")
GPKG = os.path.join(BASE, "outputs", "ontario_protected_areas.gpkg")
os.makedirs(os.path.join(BASE, "outputs"), exist_ok=True)
if os.path.exists(GPKG):
    os.remove(GPKG)

SRC = osr.SpatialReference(); SRC.ImportFromEPSG(4326)
DST = osr.SpatialReference(); DST.ImportFromEPSG(3161)
# GDAL 3 honours EPSG axis order (lat, lon for 4326); our data are lon, lat.
SRC.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
DST.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
TR = osr.CoordinateTransformation(SRC, DST)

# area reconciliation from source fields (REGULATED_AREA is in hectares)
for name in ["provincial_parks", "conservation_reserves"]:
    d = json.load(open(os.path.join(DATA, "ontario", f"{name}.geojson")))
    vals = [f["properties"].get("REGULATED_AREA") for f in d["features"]]
    tot = sum(v for v in vals if v)
    print(f"{name}: {len(vals)} features, REGULATED_AREA sum = {tot:,.0f} ha = {tot/100:,.0f} km2 "
          f"({tot/100/1076395*100:.2f}% of Ontario land area)")
    print(f"  null REGULATED_AREA: {sum(1 for v in vals if not v)}")

drv = ogr.GetDriverByName("GPKG")
gpkg = drv.CreateDataSource(GPKG)

def copy_layer(src_path, out_name, simplify_m, spat=None):
    ds = ogr.Open(src_path)
    lyr = ds.GetLayer(0)
    if spat:
        lyr.SetSpatialFilterRect(*spat)
    out = gpkg.CreateLayer(out_name, srs=DST, geom_type=lyr.GetGeomType())
    defn = lyr.GetLayerDefn()
    for i in range(defn.GetFieldCount()):
        out.CreateField(defn.GetFieldDefn(i))
    n_in = n_bad = 0
    area_m2 = 0.0
    for feat in lyr:
        n_in += 1
        g = feat.GetGeometryRef()
        if g is None:
            n_bad += 1
            continue
        g = g.Clone()
        if not g.IsValid():
            g = g.MakeValid()
        if g.Transform(TR) != 0:
            n_bad += 1
            continue
        env = g.GetEnvelope()
        # EPSG:3161 has false easting 930,000 and false northing 6,430,000,
        # so Ontario sits at roughly x 0..1,900,000, y 10,900,000..12,900,000.
        if not (-200000 < env[0] < 2000000 and 10500000 < env[2] < 13100000):
            n_bad += 1
            continue
        g_simple = g.Simplify(simplify_m)
        # Tiny features (e.g. 1 ha Kama Hills) can simplify to nothing: keep them whole.
        g = g_simple if (g_simple is not None and not g_simple.IsEmpty()) else g
        if g is None or g.IsEmpty():
            n_bad += 1
            continue
        area_m2 += g.Area()
        of = ogr.Feature(out.GetLayerDefn())
        for i in range(defn.GetFieldCount()):
            of.SetField(i, feat.GetField(i))
        of.SetGeometry(g)
        out.CreateFeature(of)
    print(f"{out_name}: {n_in} in, {n_bad} skipped, area = {area_m2/1e6:,.0f} km2")
    ds = None

copy_layer(os.path.join(DATA, "ontario_boundary.geojson"), "ontario_boundary", 200)
copy_layer(os.path.join(DATA, "ontario", "provincial_parks.geojson"), "provincial_parks", 100)
copy_layer(os.path.join(DATA, "ontario", "conservation_reserves.geojson"), "conservation_reserves", 100)
copy_layer(os.path.join(DATA, "ontario", "conservation_authorities.geojson"), "conservation_authorities", 100)
copy_layer("/home/hatch/workspace/hydrology-canada/data/ne_lakes/ne_10m_lakes.shp",
           "great_lakes", 200, spat=(-96.0, 41.0, -74.0, 57.5))
gpkg = None
print("wrote", GPKG)
