#!/usr/bin/env python3
"""
Where the toll plazas of UM-108 (toll-tariffs) are: each gazetted plaza matched by name to OpenStreetMap toll booths,
placed at the middle of its booths, with the province it falls in (OpenStreetMap's admin_level 4 boundaries).

Run it from the repo root with pyosmium and shapely from a virtual env outside the repo (nothing installed globally):

    python3 -m venv <scratch>/venv && <scratch>/venv/bin/pip install osmium shapely
    <scratch>/venv/bin/python -I scripts/datasets/toll-tariffs-locate.py --pbf <south-africa.osm.pbf> \
        --plazas data/build/toll-tariffs/plazas.json --out data/build/toll-tariffs/locations.json

The extract is Geofabrik's South Africa file (the one place-names uses, data/sources/place-names/osm/). The gazettes
name each plaza but don't say where it is, so positions and provinces come from OpenStreetMap: (c) OpenStreetMap
contributors, ODbL 1.0. Records built with them carry that attribution and are treated as ODbL. Only toll booths
whose name is one of the plaza's OSM names (plazas.json: osm_names) count; a plaza with none is left unplaced
rather than guessed. Some ramp plazas' booths carry no name in OpenStreetMap; where the ramp the booths stand on is
signed to the plaza's own place (its destination tag names it, as a plaza's ramp is named for its interchange),
plazas.json lists those booths by node id (osm_booths, with osm_booths_why saying which ramp) and they count too
(13 Nov 2026: Cullinan, Valtaki and Ekandustria on the N4 east of Pretoria). Nothing here is personal: toll booths and province boundaries only.
"""
import argparse
import hashlib
import json

import osmium
from shapely import STRtree, wkb
from shapely.geometry import Point

ap = argparse.ArgumentParser()
ap.add_argument('--pbf', required=True)
ap.add_argument('--plazas', required=True)
ap.add_argument('--out', required=True)
a = ap.parse_args()

plazas = json.load(open(a.plazas))
plazas = plazas['plazas'] if isinstance(plazas, dict) else plazas
wanted = {n for p in plazas for n in p.get('osm_names', [])}
by_id = {int(x.split('/')[1]) for p in plazas for x in p.get('osm_booths', [])}
fab = osmium.geom.WKBFactory()


class Handler(osmium.SimpleHandler):
    def __init__(self):
        super().__init__()
        self.booths, self.provinces = [], []

    def node(self, n):
        if n.tags.get('barrier') == 'toll_booth' and (n.tags.get('name') in wanted or n.id in by_id):
            self.booths.append({'osm': f'node/{n.id}', 'name': n.tags.get('name'), 'lat': n.location.lat, 'lon': n.location.lon})

    def area(self, ar):
        t = ar.tags
        if t.get('boundary') == 'administrative' and t.get('admin_level') == '4':
            self.provinces.append({'name': t.get('name'), 'osm': f"relation/{ar.orig_id()}" if not ar.from_way() else f'way/{ar.orig_id()}',
                                   'geom': wkb.loads(fab.create_multipolygon(ar), hex=True)})


h = Handler()
h.apply_file(a.pbf, locations=True, idx='flex_mem')
tree = STRtree([p['geom'] for p in h.provinces])
sha = hashlib.sha256(open(a.pbf, 'rb').read()).hexdigest()
out = {'_about': 'Toll plaza positions from OpenStreetMap toll booths (barrier=toll_booth) whose name is one of the plaza\'s osm_names (or, unnamed, on a ramp signed to the plaza\'s place: osm_booths), '
                  'averaged; province from OpenStreetMap admin_level 4 boundaries. (c) OpenStreetMap contributors, ODbL 1.0. '
                  'Made by scripts/datasets/toll-tariffs-locate.py.',
       'extract': a.pbf.split('/')[-1], 'extract_sha256': sha, 'plazas': {}}
for p in plazas:
    hits = [b for b in h.booths if (b['name'] and b['name'] in p.get('osm_names', [])) or b['osm'] in p.get('osm_booths', [])]
    if not hits:
        out['plazas'][p['key']] = None
        continue
    lat = sum(b['lat'] for b in hits) / len(hits)
    lon = sum(b['lon'] for b in hits) / len(hits)
    spread_m = max(((b['lat'] - lat) ** 2 + (b['lon'] - lon) ** 2) ** 0.5 for b in hits) * 111_000
    pt = Point(lon, lat)
    inside = [h.provinces[i] for i in tree.query(pt) if h.provinces[i]['geom'].contains(pt)]
    out['plazas'][p['key']] = {
        'latitude': round(lat, 4), 'longitude': round(lon, 4), 'spread_m': round(spread_m),
        'province': inside[0]['name'] if len(inside) == 1 else None, 'province_osm': inside[0]['osm'] if len(inside) == 1 else None,
        'osm': sorted(b['osm'] for b in hits),
    }
json.dump(out, open(a.out, 'w'), indent=1, ensure_ascii=False)
print(f"{sum(1 for v in out['plazas'].values() if v)} of {len(plazas)} plazas placed")
