import json
import time
from datetime import datetime
from amadeus import Client, ResponseError


# OopCompanion:suppressRename


class AmadeusClient:
	def __init__(self, client_id: str, client_secret: str):
		"""
		Initialize the Amadeus API client.
		"""
		self.client = Client(client_id=client_id, client_secret=client_secret,hostname="production")

	def find_cheapest_flights(self, origin: str, destination: str, departure_date: str, adults: int = 1):
		"""
		Find the cheapest flights from the origin to the destination on a specific date.

		:param origin: The IATA code for the origin location.
		:param destination: The IATA code for the destination location.
		:param departure_date: The date of departure in YYYY-MM-DD format.
		:param adults: Number of adult passengers.
		:return: Flight offers data.
		"""
		try:
			response = self.client.shopping.flight_offers_search.get(
				originLocationCode=origin,
				destinationLocationCode=destination,
				departureDate=departure_date,
				adults=adults,
				max=250,
				nonStop="true",
			)
			return response.data
		except ResponseError as error:
			if error.response.status_code == 429:
				retry_after = error.response.headers.get( 'Retry-After', '60' )  # standard fallback til 60 sekunder
				print( f"Rate limit reached. Retry after {retry_after} seconds." )
				time.sleep( int( retry_after ) )


	def parse_flight_data(self, flights):
		"""
		Parse the flight data to extract useful information about flights.

		:param flights: Raw flight offers data.
		:return: Parsed flight details.
		"""
		result = []
		for flight_offer in flights:
			itineraries = flight_offer.get("itineraries", [])
			price = float(flight_offer.get("price", {}).get("total", 0))

			for itinerary in itineraries:
				segments = itinerary.get("segments", [])
				for segment in segments:
					if segment.get("numberOfStops", -1) == 0:  # Only non-stop flights
						departure = segment.get("departure", {})
						arrival = segment.get("arrival", {})
						travel_time = (
								              datetime.fromisoformat(arrival["at"]) - datetime.fromisoformat(departure["at"])
						              ).total_seconds() / 3600

						result.append({
							"departure": {
								"iataCode": departure.get("iataCode"),
								"at": departure.get("at"),
							},
							"arrival": {
								"iataCode": arrival.get("iataCode"),
								"at": arrival.get("at"),
							},
							"travel_time": travel_time,
							"price": price,
						})
		return result

	def get_flight_summary(self, departure_date: str, origin: str, destination: str):
		"""
		Get a summary of the flight details for a specific date, origin, and destination.

		:param departure_date: The date of travel in YYYY-MM-DD format.
		:param origin: The IATA code for the origin location.
		:param destination: The IATA code for the destination location.
		:return: Formatted flight summary string.
		"""
		time.sleep(5)  # Avoid rate limiting
		flights = self.find_cheapest_flights(origin, destination, departure_date)
		parsed_flights = self.parse_flight_data(flights)
		with open("data_chunks.txt", "a") as fp:
			json.dump(parsed_flights, fp,indent = 4)
			fp.write(",")


		if not parsed_flights:
			return f"No flights found for {departure_date}: {origin} -> {destination}"

		average_price = sum(f["price"] for f in parsed_flights) / len(parsed_flights)
		first_departure = parsed_flights[0]["departure"]["iataCode"]
		last_arrival = parsed_flights[-1]["arrival"]["iataCode"]

		return f"{departure_date}: {first_departure} -> {last_arrival} - {average_price:.2f}"


# Example usage
if __name__ == "__main__":
	client_id = "ABRGQv6U7IWAYxwwmjqAOPUDGvuFMSjw"
	client_secret = "BcwpSKf3FICJIxaw"
	travel_days = [{'date': '2025-01-15', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 3, 'month': 1}, {'date': '2025-01-17', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 3, 'month': 1}, {'date': '2025-01-29', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 5, 'month': 1}, {'date': '2025-01-31', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 5, 'month': 1}, {'date': '2025-02-12', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 7, 'month': 2}, {'date': '2025-02-14', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 7, 'month': 2}, {'date': '2025-02-26', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 9, 'month': 2}, {'date': '2025-02-28', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 9, 'month': 2}, {'date': '2025-03-12', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 11, 'month': 3}, {'date': '2025-03-14', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 11, 'month': 3}, {'date': '2025-03-26', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 13, 'month': 3}, {'date': '2025-03-28', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 13, 'month': 3}, {'date': '2025-04-09', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 15, 'month': 4}, {'date': '2025-04-11', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 15, 'month': 4}, {'date': '2025-04-23', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 17, 'month': 4}, {'date': '2025-04-25', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 17, 'month': 4}, {'date': '2025-05-07', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 19, 'month': 5}, {'date': '2025-05-09', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 19, 'month': 5}, {'date': '2025-05-21', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 21, 'month': 5}, {'date': '2025-05-23', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 21, 'month': 5}, {'date': '2025-06-04', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 23, 'month': 6}, {'date': '2025-06-06', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 23, 'month': 6}, {'date': '2025-06-18', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 25, 'month': 6}, {'date': '2025-06-20', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 25, 'month': 6}, {'date': '2025-07-02', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 27, 'month': 7}, {'date': '2025-07-04', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 27, 'month': 7}, {'date': '2025-07-16', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 29, 'month': 7}, {'date': '2025-07-18', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 29, 'month': 7}, {'date': '2025-07-30', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 31, 'month': 7}, {'date': '2025-08-01', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 31, 'month': 8}, {'date': '2025-08-13', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 33, 'month': 8}, {'date': '2025-08-15', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 33, 'month': 8}, {'date': '2025-08-27', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 35, 'month': 8}, {'date': '2025-08-29', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 35, 'month': 8}, {'date': '2025-09-10', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 37, 'month': 9}, {'date': '2025-09-12', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 37, 'month': 9}, {'date': '2025-09-24', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 39, 'month': 9}, {'date': '2025-09-26', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 39, 'month': 9}, {'date': '2025-10-08', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 41, 'month': 10}, {'date': '2025-10-10', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 41, 'month': 10}, {'date': '2025-10-22', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 43, 'month': 10}, {'date': '2025-10-24', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 43, 'month': 10}, {'date': '2025-11-05', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 45, 'month': 11}, {'date': '2025-11-07', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 45, 'month': 11}, {'date': '2025-11-19', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 47, 'month': 11}, {'date': '2025-11-21', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 47, 'month': 11}, {'date': '2025-12-03', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 49, 'month': 12}, {'date': '2025-12-05', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 49, 'month': 12}, {'date': '2025-12-17', 'orgin': 'LIS', 'dest': 'CPH', 'uge': 51, 'month': 12}, {'date': '2025-12-19', 'orgin': 'CPH', 'dest': 'LIS', 'uge': 51, 'month': 12}]

	amadeus_client = AmadeusClient( client_id, client_secret )
	with open( "summery.txt", 'w' ) as fp:
		for days in travel_days:
			origin = days['orgin']
			destination = days['dest']
			departure_date = days['date']

			try:
				summary = amadeus_client.get_flight_summary( departure_date, origin, destination )
				print( summary )
				fp.writelines( summary + '\n' )
			except ResponseError as error:
				print( f"An error occurred: {error}" )

