import requests
import json
import time

def download_mel_bus_stable():
    # Switching to the 'Kumi Systems' mirror - often faster when the main one is down
    url = "https://overpass.kumi.systems/api/interpreter"
    headers = {'User-Agent': 'MEL_Bus_Downloader_Local/1.0'}
    
    # Bounding box for MEL (South-West to North-East)
    # Approx: From south of Seclin to north of Tourcoing
    bbox = "50.48,2.78,50.78,3.28"
    
    # Query using Bbox and targeting the Ilévia network specifically
    list_query = f"""
    [out:json][timeout:60];
    (
      relation["route"="bus"]["network"~"Ilévia|ilévia", i]({bbox});
    );
    out tags;
    """
    
    print(f"Attempting to reach mirror: {url}")
    try:
        response = requests.post(url, data={'data': list_query}, headers=headers, timeout=65)
        response.raise_for_status()
        routes = response.json().get('elements', [])
        
        if not routes:
            print("No routes found. The server might be returning empty data. Check connection.")
            return
            
        print(f"Success! Found {len(routes)} routes. Downloading paths...")
        
        all_features = []
        for i, route in enumerate(routes):
            rid = route['id']
            ref = route.get('tags', {}).get('ref', '??')
            
            # Fetch geometry for each relation
            single_query = f"[out:json];relation({rid});out geom;"
            
            try:
                res = requests.post(url, data={'data': single_query}, headers=headers, timeout=30)
                if res.status_code == 200:
                    elements = res.json().get('elements', [])
                    for el in elements:
                        if 'members' in el:
                            coords = []
                            for m in el['members']:
                                if 'geometry' in m:
                                    coords.append([[p['lon'], p['lat']] for p in m['geometry']])
                            
                            if coords:
                                all_features.append({
                                    "type": "Feature",
                                    "properties": el.get('tags', {}),
                                    "geometry": {"type": "MultiLineString", "coordinates": coords}
                                })
                print(f"Progress: {i+1}/{len(routes)} (Line {ref})", end="\r")
                time.sleep(0.2) # Polite delay
            except:
                continue

        # Save result
        with open("mel_bus_network.geojson", "w", encoding="utf-8") as f:
            json.dump({"type": "FeatureCollection", "features": all_features}, f, indent=4)
        
        print(f"\nFinished! Saved to mel_bus_network.geojson")

    except Exception as e:
        print(f"Mirror also timed out or failed: {e}")
        print("\nSUGGESTION: The Overpass servers are currently overloaded.")
        print("Try visiting: https://overpass-turbo.eu/")
        print("Paste this query and click 'Export' -> 'GeoJSON' manually:")
        print(list_query.replace("out tags;", "out geom;"))

if __name__ == "__main__":
    download_mel_bus_stable()