import requests
import json
import urllib3

urllib3.disable_warnings()

URL = "https://mtr.ciapongi.szablix.pl/mtr/api/map/stations-and-routes?dimension=0"
# Zapisujemy plik bezpośrednio do folderu WWW, żeby strona mogła go odczytać
OUTPUT_FILE = "/var/lib/pterodactyl/volumes/cc7ccc03-03bd-4bde-8488-3057d3803420/squaremap/web/trasy_tts.json"

def main():
    print("=== GENERATOR BAZY TRAS TTS ===")
    print("Pobieranie surowych danych z MTR...")
    
    try:
        r = requests.get(URL, verify=False, timeout=15)
        data = r.json()

        stations_raw = data.get('data', {}).get('stations', [])
        routes_raw = data.get('data', {}).get('routes', [])

        # Słownik: ID stacji -> Prawdziwa Nazwa Stacji
        station_dict = {s['id']: s['name'] for s in stations_raw}

        routes_db = {}
        for route in routes_raw:
            route_id = route['id']

            stacje_trasy = []
            for st in route.get('stations', []):
                s_id = st['id']
                prawdziwa_nazwa = station_dict.get(s_id, "Nieznana Stacja")
                peron = st.get('name', '1') # w MTR 'name' wewnątrz trasy to numer peronu
                
                stacje_trasy.append({
                    "id": s_id,
                    "name": prawdziwa_nazwa,
                    "platform": peron
                })

            # Usuwamy duplikaty stacji następujących po sobie (gdy pociąg staje na 2 peronach pod rząd)
            cleaned_stacje = []
            for st in stacje_trasy:
                if not cleaned_stacje or cleaned_stacje[-1]['id'] != st['id']:
                    cleaned_stacje.append(st)

            routes_db[route_id] = {
                "name": route.get('name', ''),
                "number": route.get('number', ''),
                "type": route.get('type', ''),
                "stations": cleaned_stacje
            }

        with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
            json.dump(routes_db, f, ensure_ascii=False, indent=2)

        print(f"Sukces! Zapisano {len(routes_db)} tras do pliku trasy_tts.json")
    
    except Exception as e:
        print(f"BŁĄD GENERATORA: {e}")

if __name__ == "__main__":
    main()
