
#!/usr/bin/env python3
"""
convert_roads.py
BoopLabs Pupmap Europe/Nordics Roads GeoJSON
Version: 2025-10-03
"""

import geopandas as gpd

# ---------- User paths ----------
roads_shp = "ne_10m_roads.shp"
output_dir = "/mnt/storage/docker-data/pupmap/www/data/"

# ---------- Europe + Nordics ISO3 ----------
europe_nordics = [
    'ALB','AND','AUT','BEL','BIH','BGR','HRV','CYP','CZE','DNK','EST','FIN','FRA','DEU',
    'GRC','HUN','ISL','IRL','ITA','LVA','LTU','LUX','MLT','MDA','MCO','MNE','NLD','NOR',
    'POL','PRT','ROU','RUS','SMR','SRB','SVK','SVN','ESP','SWE','CHE','UKR','GBR','VAT'
]

# ---------- Load roads shapefile ----------
print("Processing roads...")
roads = gpd.read_file(roads_shp)

# Filter Europe/Nordics only if ADM0_A3 exists
if 'ADM0_A3' in roads.columns:
    roads_filtered = roads[roads['ADM0_A3'].isin(europe_nordics)].copy()
else:
    roads_filtered = roads.copy()  # fallback: include all

# Determine road type column
if 'TYPE' in roads_filtered.columns:
    roads_filtered = roads_filtered.rename(columns={'TYPE': 'type'})
elif 'fclass' in roads_filtered.columns:
    roads_filtered = roads_filtered.rename(columns={'fclass': 'type'})
elif 'ROADCLASS' in roads_filtered.columns:
    roads_filtered = roads_filtered.rename(columns={'ROADCLASS': 'type'})
else:
    roads_filtered['type'] = 'road'  # fallback

# Keep only necessary columns
roads_filtered = roads_filtered[['type','geometry']]

# Remove duplicates and empty geometries
roads_filtered = roads_filtered.loc[:, ~roads_filtered.columns.duplicated()]
roads_filtered = roads_filtered[roads_filtered.geometry.notnull()]

# Save to GeoJSON
roads_geojson_path = output_dir + "roads_europe.geojson"
roads_filtered.to_file(roads_geojson_path, driver='GeoJSON')
print(f"Saved {roads_geojson_path} ({len(roads_filtered)} features)")

