import json
import requests
import time
import os

# --- KONFIGURACJA ---
# Adres API Twojego serwera MTR
API_URL = "https://mtr.ciapongi.twojstarypijany.pl/mtr/api/map/departures"

# Ścieżki (dopasowane do Twojego serwera)
BASE_PATH = "/var/lib/pterodactyl/volumes/cc7ccc03-03bd-4bde-8488-3057d3803420/squaremap/web"
STATIONS_FILE = f"{BASE_PATH}/stations.json"
OUTPUT_FILE = f"{BASE_PATH}/departures.json"

def main():
    print("--- Start: Live Departures Service ---")
    print("Naciśnij Ctrl+C aby zatrzymać.")

    while True:
        try:
            # 1. Wczytaj listę stacji, żeby znać ich ID
            if not os.path.exists(STATIONS_FILE):
                print(f"[!] Brak pliku {STATIONS_FILE}. Czekam...")
                time.sleep(10)
                continue

            with open(STATIONS_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # Wyciągamy same ID stacji
            station_ids = [s['id'] for s in data.get('stations', [])]
            
            if not station_ids:
                print("[!] Brak stacji w pliku stations.json")
                time.sleep(10)
                continue

            # 2. Pobierz odjazdy dla WSZYSTKICH stacji naraz
            # MTR API pozwala wysłać listę ID w POST
            response = requests.post(API_URL, json=station_ids, timeout=10)
            response.raise_for_status()
            departures_data = response.json()

            # 3. Zapisz do pliku, który odczyta mapa
            # Zapisujemy to atomicznie (najpierw temp, potem rename), żeby mapa nie czytała "w połowie"
            temp_file = OUTPUT_FILE + ".tmp"
            with open(temp_file, "w", encoding="utf-8") as f:
                json.dump(departures_data, f)
            
            os.replace(temp_file, OUTPUT_FILE)
            
            current_time = time.strftime("%H:%M:%S")
            print(f"[{current_time}] Zaktualizowano odjazdy dla {len(station_ids)} stacji.")

        except Exception as e:
            print(f"[!] Błąd aktualizacji: {e}")
        
        # Czekaj 10 sekund przed kolejną aktualizacją
        time.sleep(10)

if __name__ == "__main__":
    main()
