#!/usr/bin/env python3
"""Six miles deep: check the six-mile line against the water it is measured from.

  python3 verify.py six-miles.geojson
  python3 verify.py six-miles.geojson --water Waterbody.zip --water Watercourse.zip

Walks the line (layer "six_mile_line") at evenly spaced points and measures, on the ground (geodesic, GRS 80),
the distance from each point to the nearest water. With no --water, the water is the "banks" and "flow_line"
layers carried in the same file. With --water, it is the files given (GeoJSON, or the GRCA's zipped shapefiles;
a line layer with BUFFER_WIDTH is widened by half that width, its edge of water). Six statute miles = 9,656.064 m.
Needs: pip install shapely pyproj   (and pyogrio for shapefiles)
"""
import sys, json, argparse, hashlib, statistics
from shapely.geometry import shape, Point
from shapely.ops import nearest_points, unary_union
from shapely import STRtree
import pyproj

SIX = 9656.064
TO = pyproj.Transformer.from_crs(4326, 26917, always_xy=True)
BACK = pyproj.Transformer.from_crs(26917, 4326, always_xy=True)
GEOD = pyproj.Geod(ellps='GRS80')

def utm(g):
    import numpy as np, shapely
    return shapely.transform(g, lambda c: np.column_stack(TO.transform(c[:, 0], c[:, 1])))

def load_water(paths, gj):
    parts = []
    if not paths:
        for f in gj['features']:
            if f['properties'].get('layer') in ('banks', 'flow_line'):
                parts.append(utm(shape(f['geometry'])))
        return parts
    import pyogrio
    for p in paths:
        df = pyogrio.read_dataframe(p).to_crs(26917)
        for _, r in df.iterrows():
            g = r.geometry
            if g is None: continue
            bw = r.get('BUFFER_WIDTH') if hasattr(r, 'get') else None
            if g.geom_type in ('LineString', 'MultiLineString') and bw and float(bw) > 0:
                g = g.buffer(float(bw) / 2)
            parts.append(g)
    return parts

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('line'); ap.add_argument('--water', action='append'); ap.add_argument('--points', type=int, default=4000)
    a = ap.parse_args()
    raw = open(a.line, 'rb').read(); gj = json.loads(raw)
    print('Line file  ', a.line, ' SHA-256', hashlib.sha256(raw).hexdigest())
    for p in a.water or []:
        print('Water file ', p, ' SHA-256', hashlib.sha256(open(p, 'rb').read()).hexdigest())
    out, step, total = measure(gj, a.water, a.points)
    report(out, step, total)

def measure(gj, water_paths=None, points=4000):
    lines = [(f['properties'].get('grade') or '?', utm(shape(f['geometry']))) for f in gj['features'] if f['properties'].get('layer') == 'six_mile_line']
    water = load_water(water_paths, gj)
    if not lines or not water: sys.exit('No six_mile_line, or no water, in the files given.')
    tree = STRtree(water)
    total = sum(l.length for _, l in lines); step = total / points
    out = []
    for grade, l in lines:
        n = max(1, int(l.length / step))
        for i in range(n):
            p = l.interpolate((i + .5) * l.length / n)
            w = water[tree.nearest(p)]
            q = nearest_points(p, w)[1]
            (x1, y1), (x2, y2) = BACK.transform(p.x, p.y), BACK.transform(q.x, q.y)
            d = GEOD.inv(x1, y1, x2, y2)[2]
            out.append((grade, d))
    return out, step, total

def report(out, step, total):
    ds = [d for _, d in out]
    print('\nPoints measured   %d, about every %.0f m along %.1f km of line' % (len(ds), step, total / 1000))
    print('Six statute miles %.3f m' % SIX)
    print('All points        median %.2f m, from %.2f to %.2f m  (%+.2f to %+.2f m of six miles)' % (statistics.median(ds), min(ds), max(ds), min(ds) - SIX, max(ds) - SIX))
    for g in sorted(set(x for x, _ in out)):
        s = [d for x, d in out if x == g]
        print('Grade %s           %4d points, median %.2f m, from %.2f to %.2f m' % (g, len(s), statistics.median(s), min(s), max(s)))
    within = sum(1 for d in ds if abs(d - SIX) <= 1.5)
    print('Within 1.5 m      %d of %d points (%.1f%%)' % (within, len(ds), 100 * within / len(ds)))

if __name__ == '__main__':
    main()
