#!/usr/bin/python3.12

import logging
import sys
import time
import os
import csv
import time
import datetime as dt
from zoneinfo import ZoneInfo
from deutsche_bahn_api import ApiAuthentication, StationHelper
from deutsche_bahn_api import TimetableHelper
from datetime import datetime 


def run_download():
	
	
	os.environ['TZ'] = 'Europe/Berlin'
	
	berlin_tz = ZoneInfo("Europe/Berlin")
	
	sbahn_hannover_stations = [
			"Ahlten", "Aligse", "Altenbeken", "Bad Münder(Deister)", "Bad Nenndorf", 
			"Bad Pyrmont", "Bantorf", "Barnten", "Barsinghausen", "Bennigsen", 
			"Bennemühlen", "Bissendorf", "Bückeburg", "Burgdorf", "Celle", 
			"Dedensen-Gümmer", "Egestorf(Deister)", "Ehlershausen", "Eilvese", "Emmerke", 
			"Emmerthal", "Empelde", "Hagen(Han)", "Hameln", "Hannover Anderten-Misburg", 
			"Hannover Bismarckstr.", "Hannover-Bornum", "Hannover Flughafen", "Hannover Hbf", 
			"Hannover Karl-Wiechert-Allee", "Hannover-Kleefeld", "Hannover-Ledeburg", 
			"Hannover-Leinhausen", "Hannover-Linden/Fischerhof", "Hannover Messe/Laatzen", 
			"Hannover-Nordstadt", "Hannover-Vinnhorst", "Harsum", "Haste", "Hildesheim Hbf", 
			"Holtensen/Linderte", "Kirchdorf(Deister)", "Kirchhorsten", "Langenhagen-Kaltenweide", 
			"Langenhagen Mitte", "Langenhagen Pferdemarkt", "Lehrte", "Lemmie", "Letter", 
			"Lindhorst(Schaumb-Lippe)", "Linsburg", "Lügde", "Mellendorf", "Minden(Westf)", 
			"Neustadt am Rübenberge", "Nienburg(Weser)", "Otze", "Paderborn Hbf", "Poggenhagen", 
			"Rethen(Leine)", "Ronnenberg", "Sarstedt", "Schieder", "Seelze", "Sehnde", 
			"Springe", "Stadthagen", "Steinheim(Westf)", "Völksen/Eldagsen", "Weetzen", 
			"Wennigsen(Deister)", "Winninghausen", "Wunstorf"]

	
	sbahn_hannover_terminal_stations = [
		"Bad Nenndorf",
		"Barsinghausen",
		"Bennemühlen",
		"Celle",
		"Hameln",
		"Hannover Flughafen",
		"Hannover Hbf",
		"Hannover Messe/Laatzen",
		"Haste",
		"Hildesheim Hbf",
		"Minden(Westf)",
		"Nienburg(Weser)",
		"Paderborn Hbf",
		"Seelze"
	]
	
	
	logging.info(f"Starting download delays for {len(sbahn_hannover_stations)} stations...")
	
	date_format = "%y%m%d%H%M"

	script_path = os.path.dirname(os.path.abspath(__file__))

	api_authentication = ApiAuthentication(
		"bbf5eca4a43deb5f46b132bedf729521",
		"326641a6bba05433e55c7cc2bf864d91")
	flagsuccess = api_authentication.test_credentials()
	
	station_helper = StationHelper()
	
	for station_name in sbahn_hannover_stations:
		try:
			
			# Search for the station
			found_stations_by_name = station_helper.find_stations_by_name(station_name)

			station = found_stations_by_name[0]

			filename = f"{datetime.today().strftime('%Y%m%d')}_data.csv"

			with open(os.path.join(script_path,"output",filename), mode='a', newline='', encoding='utf-8') as f:
				writer = csv.writer(f)
				header = ['LookupDate','Line','Station','ScheduledDeparture', 'Delay', 'ScheduledDestination', 'ChangedDestination']
				writer.writerow(header)

				date_lookup = dt.datetime.now(berlin_tz).strftime(date_format)


				timetable_helper = TimetableHelper(station, api_authentication)
				trains_in_this_hour = timetable_helper.get_timetable()
				trains_with_changes = timetable_helper.get_timetable_changes(trains_in_this_hour)
				for train_in_this_hour in trains_with_changes:
					if train_in_this_hour.train_type == "SBH":
						train_line = f"{train_in_this_hour.train_type}_{train_in_this_hour.train_line}"
						train_destination = train_in_this_hour.stations
						time_scheduled = train_in_this_hour.departure
						
						
						dt1 = dt.datetime.strptime(time_scheduled, date_format)

						if hasattr(train_in_this_hour.train_changes,'departure'):
							
							time_delayed = train_in_this_hour.train_changes.departure
					
							dt2 = dt.datetime.strptime(time_delayed, date_format)
							delta = dt2 - dt1
							minutes_diff = delta.total_seconds() / 60
							if hasattr(train_in_this_hour.train_changes,'stations'):
								train_change_destination = train_in_this_hour.train_changes.stations
							else:
								train_change_destination = "NA" 
						else:
							minutes_diff = "Cancelled"		

						train_destination = train_destination.split('|')[-1].strip()
						train_change_destination = train_change_destination.split('|')[-1].strip()

						new_data = [date_lookup, train_line, station_name, time_scheduled, minutes_diff, train_destination, train_change_destination]
						writer.writerow(new_data)
						f.flush()
		except Exception as e:
			logging.info(f"Error searching for {station_name}: {e}")


if __name__ == "__main__":
	log_file = sys.argv[1]
	logging.basicConfig(
		filename = log_file,
		level = logging.INFO,
		format = "%(asctime)s ¦ %(levelname)s ¦ %(message)s"
	)	
	logging.info("Subprocess Download Delays started")
	try:
		run_download()
	except Exception as e:
		logging.info(f"Error in subprocess: {e}")
	logging.info("Subprocess Download Delays finished")
