GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / repd_grid_atlasv6/scripts

Fetch Eurostar v6 and 4 more files

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

551 lines of Python from globalgrid2050, in 5 files. Topic: Maps, GIS and field navigation. Section 494 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Fetch Airports v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_airportsv6.py lines 1–71
  2. Fetch Datacentres v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_datacentresv6.py lines 1–75
  3. Fetch Elizabeth Line v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_elizabeth_linev6.py lines 1–121
  4. Fetch Eurostar v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_eurostarv6.py lines 1–170
  5. Fetch EV Chargers v6 storage · globalgrid2050 / repd_grid_atlasv6/scripts/fetch_ev_chargersv6.py lines 1–114

Fetch Airports v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_airportsv6.py · lines 1–71 of 71 · Entry point

What it does
It fetches data. Defines fetch_airports. Uses libraries requests, json, time. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: GeoJSON file airports.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it fetches airports. Defines `fetch_airports`. It writes `airports.geojson`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, time
Used by
none found
Produces
fetch_airports
Defines here
fetch_airports
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_airportsv6.py:1-71 · blob 550a36094eb73966f8aa000b66c14e8d1f6c4179 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import time

def fetch_airports():
    print("🚀 Fetching UK Airports from OpenStreetMap...")
    
    query = """
    [out:json][timeout:180];
    area(3600062149)->.uk;
    (
      node["aeroway"="aerodrome"](area.uk);
      way["aeroway"="aerodrome"](area.uk);
      relation["aeroway"="aerodrome"](area.uk);
    );
    out center;
    """
    
    url = "https://overpass-api.de/api/interpreter"
    
    for attempt in range(3):
        try:
            response = requests.post(url, data={'data': query})
            if response.status_code == 200:
                print("  ✅ Download successful!")
                break
            elif response.status_code == 429:
                print("  ⚠️ Server busy, sleeping 60s...")
                time.sleep(60)
            else:
                print(f"  ❌ Error: {response.status_code}")
                return
        except Exception as e:
            print(f"  ❌ Connection Error: {e}")
            return

    osm_data = response.json()
    geojson = {"type": "FeatureCollection", "features": []}
    
    for element in osm_data.get('elements', []):
        tags = element.get('tags', {})
        
        if element['type'] == 'node':
            lat, lon = element.get('lat'), element.get('lon')
        elif 'center' in element:
            lat, lon = element['center'].get('lat'), element['center'].get('lon')
        else:
            continue
            
        if lat and lon:
            # Filter out tiny private helipads/grass strips if they don't have a name
            if 'name' in tags or 'iata' in tags or 'icao' in tags:
                feature = {
                    "type": "Feature",
                    "properties": {
                        "name": tags.get('name', 'Unknown Airport'),
                        "iata": tags.get('iata', 'N/A'),
                        "icao": tags.get('icao', 'N/A')
                    },
                    "geometry": {"type": "Point", "coordinates": [lon, lat]}
                }
                geojson['features'].append(feature)

    with open("airports.geojson", 'w', encoding='utf-8') as f:
        json.dump(geojson, f)
        
    print(f"🎉 Successfully saved {len(geojson['features'])} Airports to airports.geojson!")

if __name__ == "__main__":
    fetch_airports()

Fetch Datacentres v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_datacentresv6.py · lines 1–75 of 75 · Entry point

What it does
It fetches data. Defines fetch_data_centres. Uses libraries requests, json, time. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: GeoJSON file datacentres.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it fetches datacentres. Defines `fetch_data_centres`. It writes `datacentres.geojson`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, time
Used by
none found
Produces
fetch_data_centres
Defines here
fetch_data_centres
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_datacentresv6.py:1-75 · blob 989255cd41b30bd14a9f7490767b57d4af070ebc · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import time

def fetch_data_centres():
    print("🚀 Fetching UK Data Centres from OpenStreetMap...")
    
    # We look for both telecom=data_center and building=data_center tags
    query = """
    [out:json][timeout:180];
    area(3600062149)->.uk;
    (
      node["telecom"="data_center"](area.uk);
      way["telecom"="data_center"](area.uk);
      relation["telecom"="data_center"](area.uk);
      
      node["building"="data_center"](area.uk);
      way["building"="data_center"](area.uk);
      relation["building"="data_center"](area.uk);
    );
    out center;
    """
    
    url = "https://overpass-api.de/api/interpreter"
    
    for attempt in range(3):
        try:
            response = requests.post(url, data={'data': query})
            if response.status_code == 200:
                print("  ✅ Download successful!")
                break
            elif response.status_code == 429:
                print("  ⚠️ Server busy, sleeping 60s...")
                time.sleep(60)
            else:
                print(f"  ❌ Error: {response.status_code}")
                return
        except Exception as e:
            print(f"  ❌ Connection Error: {e}")
            return

    osm_data = response.json()
    geojson = {"type": "FeatureCollection", "features": []}
    
    for element in osm_data.get('elements', []):
        tags = element.get('tags', {})
        
        # Get coordinates whether it's a node or the center of a building polygon
        if element['type'] == 'node':
            lat, lon = element.get('lat'), element.get('lon')
        elif 'center' in element:
            lat, lon = element['center'].get('lat'), element['center'].get('lon')
        else:
            continue
            
        if lat and lon:
            feature = {
                "type": "Feature",
                "properties": {
                    "name": tags.get('name', 'Unknown Data Centre'),
                    "operator": tags.get('operator', tags.get('brand', 'Unknown Operator')),
                },
                "geometry": {"type": "Point", "coordinates": [lon, lat]}
            }
            geojson['features'].append(feature)

    # Save the file
    with open("datacentres.geojson", 'w', encoding='utf-8') as f:
        json.dump(geojson, f)
        
    print(f"🎉 Successfully saved {len(geojson['features'])} Data Centres to datacentres.geojson!")

if __name__ == "__main__":
    fetch_data_centres()

Fetch Elizabeth Line v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_elizabeth_linev6.py · lines 1–121 of 121 · Entry point · pattern handle_element (shared by 2 files)

What it does
It fetches data. Defines 6 functions or classes, including build_query, centroid, way_to_ring, process_data, handle_element. Uses libraries requests, json, math. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: GeoJSON file elizabeth_line.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It builds query (`build_query`) and is built from the centroid step (`centroid`) and the way to ring helper (`way_to_ring`). Use the primary, fast Overpass API endpoint. It writes `elizabeth_line.geojson`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, math
Used by
none found
Produces
build_query, centroid, way_to_ring, process_data, main
Defines here
build_query, centroid, way_to_ring, process_data, handle_element, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_elizabeth_linev6.py:1-121 · blob a9add21876a121f424164b11b4d8c2fa94bfb5b7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import math

# Use the primary, fast Overpass API endpoint
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
BBOX = "49.5,-10.8,61.0,2.2"

def build_query() -> str:
    # Searches for stations/halts where the network or line is explicitly tagged as Elizabeth line
    blocks = (
        f'node["railway"~"station|halt"]["network"~"Elizabeth line",i]({BBOX});\n'
        f'way["railway"~"station|halt"]["network"~"Elizabeth line",i]({BBOX});\n'
        f'relation["railway"~"station|halt"]["network"~"Elizabeth line",i]({BBOX});\n'
        f'node["railway"~"station|halt"]["line"~"Elizabeth line",i]({BBOX});\n'
        f'way["railway"~"station|halt"]["line"~"Elizabeth line",i]({BBOX});\n'
        f'relation["railway"~"station|halt"]["line"~"Elizabeth line",i]({BBOX});\n'
    )
    return f"[out:json][timeout:90];\n(\n{blocks});\nout body;\n>;\nout skel qt;\n"

def centroid(coords: list) -> tuple:
    return (sum(c[0] for c in coords) / len(coords), sum(c[1] for c in coords) / len(coords))

def way_to_ring(way: dict, nodes: dict):
    coords = []
    for nid in way.get("nodes", []):
        if nid in nodes:
            node = nodes[nid]
            coords.append((node["lon"], node["lat"]))
    if len(coords) < 3: return None
    if coords[0] != coords[-1]: coords.append(coords[0])
    return coords

def process_data(data: dict) -> list:
    elements = data.get("elements", [])
    nodes = {el["id"]: el for el in elements if el["type"] == "node"}
    ways = {el["id"]: el for el in elements if el["type"] == "way" and "tags" in el}
    relations = [el for el in elements if el["type"] == "relation" and "tags" in el]
    
    features = []
    seen = set()

    def handle_element(el_id, tags, lon, lat):
        if el_id in seen: return
        seen.add(el_id)
        
        name = tags.get("name", "Unnamed Station")
        operator = tags.get("operator", "Transport for London")
        
        features.append({
            "type": "Feature",
            "properties": {
                "name": name,
                "operator": operator,
                "osm_id": el_id,
                "type": "elizabeth_line_station"
            },
            "geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]}
        })

    # Process Nodes
    for node in nodes.values():
        if "tags" in node:
            handle_element(node["id"], node["tags"], node["lon"], node["lat"])

    # Process Ways (Station buildings/polygons)
    for way in ways.values():
        ring = way_to_ring(way, nodes)
        if ring:
            c_lon, c_lat = centroid(ring)
            handle_element(way["id"], way["tags"], c_lon, c_lat)

    # Process Relations (Complex station layouts)
    for rel in relations:
        outer_coords = []
        for member in rel.get("members", []):
            if member["type"] == "way" and member.get("role") in ("outer", ""):
                w = ways.get(member["ref"])
                if w:
                    ring = way_to_ring(w, nodes)
                    if ring: outer_coords.extend(ring)
        if outer_coords:
            c_lon, c_lat = centroid(outer_coords)
            handle_element(rel["id"], rel["tags"], c_lon, c_lat)

    return features

def main():
    print("Fetching Elizabeth Line stations...")
    query = build_query()
    try:
        res = requests.post(OVERPASS_URL, data={"data": query}, timeout=90)
        res.raise_for_status()
        raw_data = res.json()
    except Exception as e:
        print(f"Error fetching data: {e}")
        return
        
    features = process_data(raw_data)
    
    # Deduplicate overlapping nodes and ways (within ~150m)
    tol = 150.0 / 111320.0
    kept = []
    for f in features:
        lon, lat = f["geometry"]["coordinates"]
        dup = False
        for k in kept:
            klon, klat = k["geometry"]["coordinates"]
            if abs(lon - klon) < tol and abs(lat - klat) < tol:
                dup = True
                break
        if not dup: kept.append(f)

    geojson = {"type": "FeatureCollection", "features": kept}
    with open("elizabeth_line.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
        
    print(f"Saved {len(kept)} stations to elizabeth_line.geojson")

if __name__ == "__main__":
    main()

Fetch Eurostar v6

A Python command-line tool in the scripts folder of GlobalGrid2050 using data from OpenStreetMap (Overpass).

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_eurostarv6.py · lines 1–170 of 170 · Entry point · pattern way_to_ring (shared by 4 files)

What it does
It fetches data. Defines 6 functions or classes, including build_query, centroid, way_to_ring, process_data, handle_station. Uses libraries requests, json. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: OpenStreetMap (Overpass). Out: GeoJSON file eurostar.geojson; JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It builds query (`build_query`) and is built from the centroid step (`centroid`) and the way to ring helper (`way_to_ring`). Use the primary, fast Overpass API endpoint. It writes `eurostar.geojson`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json
Used by
none found
Produces
build_query, centroid, way_to_ring, process_data, main
Defines here
build_query, centroid, way_to_ring, process_data, handle_station, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_eurostarv6.py:1-170 · blob adf13c99a00fc5e611b203f9d77fd78aff0c65ad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json

# Use the primary, fast Overpass API endpoint
OVERPASS_URL = "https://overpass-api.de/api/interpreter"

def build_query() -> str:
    # 1. Target all Eurostar route relations
    # 2. Ask for the full line geometry (out geom)
    # 3. Ask for the station nodes/platforms
    return """[out:json][timeout:90];
    (
      relation["route"="train"]["network"~"Eurostar",i];
      relation["route"="train"]["operator"~"Eurostar",i];
    )->.eurostar_routes;
    
    // Output the physical track geometries!
    .eurostar_routes out geom;
    
    // Output the station footprint geometries
    (
      node(r.eurostar_routes:"stop");
      node(r.eurostar_routes:"stop_entry_only");
      node(r.eurostar_routes:"stop_exit_only");
      node(r.eurostar_routes:"platform");
      way(r.eurostar_routes:"platform");
      relation(r.eurostar_routes:"platform");
    );
    out body;
    >;
    out skel qt;
    """

def centroid(coords: list) -> tuple:
    return (sum(c[0] for c in coords) / len(coords), sum(c[1] for c in coords) / len(coords))

def way_to_ring(way: dict, nodes: dict):
    coords = []
    for nid in way.get("nodes", []):
        if nid in nodes:
            node = nodes[nid]
            coords.append((node["lon"], node["lat"]))
    if len(coords) < 3: return None
    if coords[0] != coords[-1]: coords.append(coords[0])
    return coords

def process_data(data: dict) -> list:
    elements = data.get("elements", [])
    nodes = {el["id"]: el for el in elements if el["type"] == "node"}
    ways = {el["id"]: el for el in elements if el["type"] == "way" and "tags" in el}
    relations = [el for el in elements if el["type"] == "relation" and "tags" in el]
    
    features = []
    seen = set()

    def handle_station(el_id, tags, lon, lat):
        if el_id in seen: return
        seen.add(el_id)
        
        name = tags.get("name", tags.get("description", "Eurostar Station"))
        operator = tags.get("operator", "Eurostar")
        
        features.append({
            "type": "Feature",
            "properties": {
                "name": name,
                "operator": operator,
                "osm_id": el_id,
                "type": "eurostar_station" # Matches point layer config
            },
            "geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]}
        })

    # Process Nodes (Stations)
    for node in nodes.values():
        if "tags" in node:
            handle_station(node["id"], node["tags"], node["lon"], node["lat"])

    # Process Ways (Station platforms/buildings)
    for way in ways.values():
        if way.get("tags", {}).get("public_transport") in ("platform", "station") or way.get("tags", {}).get("railway") == "platform":
            ring = way_to_ring(way, nodes)
            if ring:
                c_lon, c_lat = centroid(ring)
                handle_station(way["id"], way["tags"], c_lon, c_lat)

    # Process Relations (Routes vs Complex Stations)
    for rel in relations:
        tags = rel.get("tags", {})
        
        # 1. EXTRACT THE TRACK ROUTE GEOMETRIES
        if tags.get("route") == "train":
            multiline = []
            for member in rel.get("members", []):
                if member["type"] == "way" and "geometry" in member:
                    line = [[pt["lon"], pt["lat"]] for pt in member["geometry"]]
                    if len(line) >= 2:
                        multiline.append(line)
            
            if multiline:
                features.append({
                    "type": "Feature",
                    "properties": {
                        "name": tags.get("name", "Eurostar Route"),
                        "operator": tags.get("operator", "Eurostar"),
                        "osm_id": rel["id"],
                        "type": "route" # Matches line layer config!
                    },
                    "geometry": {
                        "type": "MultiLineString",
                        "coordinates": multiline
                    }
                })
        
        # 2. Extract MultiPolygon Stations
        else:
            outer_coords = []
            for member in rel.get("members", []):
                if member["type"] == "way" and member.get("role") in ("outer", ""):
                    w = ways.get(member["ref"])
                    if w:
                        ring = way_to_ring(w, nodes)
                        if ring: outer_coords.extend(ring)
            if outer_coords:
                c_lon, c_lat = centroid(outer_coords)
                handle_station(rel["id"], rel["tags"], c_lon, c_lat)

    return features

def main():
    print("Fetching Eurostar routes and stations across Europe...")
    query = build_query()
    try:
        res = requests.post(OVERPASS_URL, data={"data": query}, timeout=90)
        res.raise_for_status()
        raw_data = res.json()
    except Exception as e:
        print(f"Error fetching data: {e}")
        return
        
    features = process_data(raw_data)
    
    # Deduplicate overlapping nodes and platforms (within ~200m)
    tol = 200.0 / 111320.0
    kept = []
    
    for f in features:
        # Do not attempt to deduplicate or modify LineStrings!
        if f["geometry"]["type"] == "MultiLineString":
            kept.append(f)
            continue
            
        lon, lat = f["geometry"]["coordinates"]
        dup = False
        for k in kept:
            if k["geometry"]["type"] == "Point":
                klon, klat = k["geometry"]["coordinates"]
                if abs(lon - klon) < tol and abs(lat - klat) < tol:
                    dup = True
                    break
        if not dup: kept.append(f)

    geojson = {"type": "FeatureCollection", "features": kept}
    with open("eurostar.geojson", "w", encoding="utf-8") as f:
        json.dump(geojson, f, ensure_ascii=False, separators=(",", ":"))
        
    print(f"Saved {len(kept)} Eurostar features (routes and stations) to eurostar.geojson")

if __name__ == "__main__":
    main()

Fetch EV Chargers v6

A Python command-line tool in the scripts folder of GlobalGrid2050.

storageglobalgrid2050 / repd_grid_atlasv6/scripts/fetch_ev_chargersv6.py · lines 1–114 of 114 · Entry point

What it does
It fetches data. Defines fetch_ev_chargers. Uses libraries requests, json, time, os. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: GeoJSON file ev_chargers.geojson. Out: JSON file.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Its name says it fetches EV chargers. Defines `fetch_ev_chargers`. Its code works with 100 kW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · repd_grid_atlasv6/scripts · Python CLI
Uses
requests, json, time, os
Used by
none found
Produces
fetch_ev_chargers
Defines here
fetch_ev_chargers
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 repd_grid_atlasv6/scripts/fetch_ev_chargersv6.py:1-114 · blob bc4008a097156a9894584314aacbdd84ee7d2600 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import json
import time

MIN_KW = 100
OUTPUT_FILE = "ev_chargers.geojson"
API_URL = "https://api.openchargemap.io/v3/poi/"

def fetch_ev_chargers():
    print("🚀 Fetching UK EV Rapid Chargers (100kW+) from Open Charge Map...")

    params = {
        'output': 'json',
        'countrycode': 'GB',
        'minpowerkw': MIN_KW,
        'maxresults': 10000,
        'compact': True,
        'verbose': False,
        'key': ''  # Works without key but rate limited — add OCM_API_KEY env var
    }

    import os
    api_key = os.environ.get('OCM_API_KEY', '')
    if api_key:
        params['key'] = api_key

    for attempt in range(3):
        try:
            response = requests.get(API_URL, params=params, timeout=60)
            if response.status_code == 200:
                print("  ✅ Download successful!")
                break
            elif response.status_code == 429:
                print("  ⚠️ Rate limited, sleeping 60s...")
                time.sleep(60)
            else:
                print(f"  ❌ Error: {response.status_code}")
                return
        except Exception as e:
            print(f"  ❌ Connection Error: {e}")
            return

    raw = response.json()
    print(f"  📦 Received {len(raw)} raw records")

    geojson = {"type": "FeatureCollection", "features": []}
    skipped = 0

    for item in raw:
        try:
            addr = item.get('AddressInfo', {})
            lat = addr.get('Latitude')
            lon = addr.get('Longitude')

            if not lat or not lon:
                skipped += 1
                continue

            # UK bounding box
            if not (-9.0 <= lon <= 2.5 and 49.0 <= lat <= 61.0):
                skipped += 1
                continue

            # Max power across all connections
            connections = item.get('Connections', [])
            max_kw = 0
            connector_types = set()
            for conn in connections:
                kw = conn.get('PowerKW') or 0
                if kw > max_kw:
                    max_kw = kw
                ct = conn.get('ConnectionType', {})
                if ct and ct.get('Title'):
                    connector_types.add(ct['Title'])

            if max_kw < MIN_KW:
                skipped += 1
                continue

            name = addr.get('Title', 'Unknown Charger')
            operator_info = item.get('OperatorInfo') or {}
            operator = operator_info.get('Title', 'Unknown Operator')
            status_type = item.get('StatusType') or {}
            status = status_type.get('Title', 'Unknown')

            feature = {
                "type": "Feature",
                "properties": {
                    "name": name,
                    "operator": operator,
                    "power_kw": round(max_kw, 1),
                    "connectors": ', '.join(sorted(connector_types)),
                    "status": status,
                    "type": "EV Rapid"
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": [round(lon, 6), round(lat, 6)]
                }
            }
            geojson['features'].append(feature)

        except Exception as e:
            skipped += 1
            continue

    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        json.dump(geojson, f)

    print(f"  ⏭️ Skipped {skipped} invalid records")
    print(f"🎉 Successfully saved {len(geojson['features'])} EV rapid chargers!")

if __name__ == "__main__":
    fetch_ev_chargers()