#!/usr/bin/env python3
"""SWO — nearby places (POI) extract from an OpenStreetMap PBF (track B 2026-11-28, national v2 2026-11-28).

This file IS the published method to recreate SWO's derived POI database (ODbL 4.6): the category rules below,
applied to the Geofabrik extract for Poland and the PRG gmina boundaries (GUGiK, public), give exactly the CSV SWO
imports with `php artisan swo:poi:import`.

Usage (workstation, never on the web server):
    python3 -I extract_poi.py <poland.osm.pbf> <gminy.json> <out.csv> <stats.json>
<gminy.json> is `php artisan swo:geo:export-gminy` (PRG gmina rings, [lng, lat], even-odd rule).
Needs pyosmium and shapely (own venv). Output columns:
    category,osm_ref,name,lat,lng,woj
Points are nodes as they are; areas (closed ways, multipolygons) give the centre of their bounding box.
Only the tags below are read; no address, no person, no opening hours or other attributes are kept.

Cleaning (each step counted in <stats.json>):
  * outside Poland: a point in no PRG gmina (the Geofabrik extract has a buffer over the border) is dropped;
  * the same object mapped twice (a node inside its own area, e.g. a school as a point and as a building):
    same category and same name within 100 m -> one point (the node is kept);
  * unnamed objects of the same category within 25 m -> one point;
  * bus/tram stops with the same name within 150 m (the two directions of one stop) -> one point.
Data © OpenStreetMap contributors, ODbL 1.0 (https://www.openstreetmap.org/copyright).
"""
import csv
import json
import math
import sys
import unicodedata

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

# category -> list of (key, values). First match wins. Keep in sync with App\Support\Nearby\PoiCategories.
RULES = [
    ('school', [('amenity', {'school'})]),
    ('nursery', [('amenity', {'childcare'})]),
    ('kindergarten', [('amenity', {'kindergarten'})]),
    ('grocery', [('shop', {'supermarket', 'convenience', 'greengrocer', 'bakery', 'butcher'})]),
    ('pharmacy', [('amenity', {'pharmacy'})]),
    ('clinic', [('amenity', {'clinic', 'doctors'})]),
    ('hospital', [('amenity', {'hospital'})]),
    ('tram_stop', [('railway', {'tram_stop'})]),
    ('train_station', [('railway', {'station', 'halt'})]),
    ('bus_station', [('amenity', {'bus_station'})]),
    ('bus_stop', [('highway', {'bus_stop'})]),
    ('park', [('leisure', {'park'})]),
    ('playground', [('leisure', {'playground'})]),
    ('sport', [('leisure', {'sports_centre', 'fitness_centre', 'swimming_pool', 'stadium', 'ice_rink'})]),
    ('office', [('amenity', {'townhall'}), ('office', {'government'})]),
    ('post_office', [('amenity', {'post_office'})]),
    ('library', [('amenity', {'library'})]),
    ('parking', [('amenity', {'parking'})]),
    ('fuel', [('amenity', {'fuel'})]),
]
STOPS = ('bus_stop', 'tram_stop')
POLAND_BBOX = (48.9, 14.0, 55.0, 24.3)  # min lat, min lng, max lat, max lng


def category(tags):
    if tags.get('railway') in ('station', 'halt'):
        if tags.get('station') == 'subway':
            return 'metro'  # Subway stations are railway=station in OSM; SWO calls them metro.
        if tags.get('station') in ('light_rail', 'monorail', 'funicular'):
            return None
    # In Poland a "żłobek" is often tagged as a kindergarten; its name says what it is.
    if tags.get('amenity') == 'kindergarten' and 'żłob' in (tags.get('name') or '').lower():
        return 'nursery'
    for cat, conds in RULES:
        for key, values in conds:
            if tags.get(key) in values:
                return cat
    return None


def clean_name(tags):
    name = (tags.get('name') or '').replace('\n', ' ').replace('\r', ' ').strip()
    return name[:120]


def norm(name):
    s = unicodedata.normalize('NFKD', name.lower())
    return ''.join(c for c in s if c.isalnum())


def metres(lat1, lng1, lat2, lng2):
    x = math.radians(lng2 - lng1) * math.cos(math.radians((lat1 + lat2) / 2))
    return 6371000 * math.hypot(x, math.radians(lat2 - lat1))


class Handler(osmium.SimpleHandler):
    def __init__(self):
        super().__init__()
        self.points = []  # [cat, ref, name, lat, lng, is_node]
        self.outside_bbox = 0

    def put(self, cat, ref, name, lat, lng, node):
        if not (POLAND_BBOX[0] <= lat <= POLAND_BBOX[2] and POLAND_BBOX[1] <= lng <= POLAND_BBOX[3]):
            self.outside_bbox += 1
            return
        self.points.append([cat, ref, name, lat, lng, node])

    def node(self, n):
        cat = category(n.tags)
        if cat and n.location.valid():
            self.put(cat, f'n{n.id}', clean_name(n.tags), n.location.lat, n.location.lon, True)

    def area(self, a):
        cat = category(a.tags)
        if not cat or cat in STOPS:
            return
        lats, lngs = [], []
        for ring in a.outer_rings():
            for nd in ring:
                if nd.location.valid():
                    lats.append(nd.location.lat)
                    lngs.append(nd.location.lon)
        if lats:
            ref = (f'w{a.orig_id()}' if a.from_way() else f'r{a.orig_id()}')
            self.put(cat, ref, clean_name(a.tags), (min(lats) + max(lats)) / 2, (min(lngs) + max(lngs)) / 2, False)


def load_gminy(path):
    polys, codes = [], []
    for g in json.load(open(path, encoding='utf-8')):
        shape = None
        for ring in g['rings']:
            if len(ring) < 4:
                continue
            p = Polygon(ring).buffer(0)
            shape = p if shape is None else shape.symmetric_difference(p)  # even-odd, as App\Support\Geo\AdminUnits
        if shape is not None and not shape.is_empty:
            polys.append(shape)
            codes.append(g['teryt'])
    return STRtree(polys), polys, codes


def dedupe(points, stats):
    """points sorted nodes first; returns kept points. Grid of ~200 m cells."""
    grid = {}
    kept = []
    cell = 0.002
    for p in sorted(points, key=lambda p: (not p[5], p[1])):
        cat, ref, name, lat, lng = p[:5]
        key = norm(name)
        limit = 150 if cat in STOPS and key else (100 if key else 25)
        gx, gy = int(lat / cell), int(lng / cell)
        dup = False
        for dx in (-1, 0, 1):
            for dy in (-2, -1, 0, 1, 2):
                for q in grid.get((gx + dx, gy + dy), ()):
                    if q[0] == cat and norm(q[2]) == key and metres(lat, lng, q[3], q[4]) <= limit:
                        dup = True
                        break
                if dup:
                    break
            if dup:
                break
        if dup:
            reason = 'duplicate_stop_direction' if cat in STOPS else ('duplicate_named' if key else 'duplicate_unnamed')
            stats[reason] = stats.get(reason, 0) + 1
            continue
        grid.setdefault((gx, gy), []).append(p)
        kept.append(p)
    return kept


def main():
    if len(sys.argv) != 5:
        print(__doc__)
        return 2
    pbf, gminy, out, stats_path = sys.argv[1:]
    h = Handler()
    h.apply_file(pbf, locations=True, idx='flex_mem')
    stats = {'read': len(h.points) + h.outside_bbox, 'outside_bbox': h.outside_bbox}
    tree, polys, codes = load_gminy(gminy)
    located = []
    outside = 0
    for p in h.points:
        pt = Point(p[4], p[3])
        hit = None
        for i in tree.query(pt):
            if polys[i].covers(pt):
                hit = codes[i]
                break
        if hit is None:
            outside += 1
            continue
        located.append(p + [hit[:2]])
    stats['outside_poland'] = outside
    kept = dedupe(located, stats)
    by_woj = {}
    with open(out, 'w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(['category', 'osm_ref', 'name', 'lat', 'lng', 'woj'])
        for cat, ref, name, lat, lng, _, woj in sorted(kept, key=lambda p: (p[6], p[0], p[1])):
            w.writerow([cat, ref, name, f'{lat:.6f}', f'{lng:.6f}', woj])
            by_woj.setdefault(woj, {}).setdefault(cat, 0)
            by_woj[woj][cat] += 1
    stats['written'] = len(kept)
    stats['by_woj'] = by_woj
    json.dump(stats, open(stats_path, 'w', encoding='utf-8'), indent=1, sort_keys=True)
    print(f"{len(kept)} points -> {out}; dropped: outside bbox {h.outside_bbox}, outside Poland {outside}, "
          f"duplicates {sum(v for k, v in stats.items() if k.startswith('duplicate'))}")
    return 0


if __name__ == '__main__':
    sys.exit(main())
