from amadeus import Client, ResponseError
import pandas as pd


class FlightFilter:
	def __init__(self, api_key, api_secret):
		self.amadeus = Client(client_id=api_key, client_secret=api_secret)

	def get_flight_offers(self, request_body):
		try:
			print("Fetching flight offers with the provided request body...")
			response = self.amadeus.shopping.flight_offers_search.post(request_body)
			return response.data
		except ResponseError as error:
			print(f"Error fetching flight offers: {error}")
			print("Response Details:", error.response.body)  # Add this line for detailed error logging
			return []

	def filter_flights(self, flights, origin, destination):
		"""
		Filters flights by origin and destination.
		"""
		filtered_flights = []
		for offer in flights:
			for itinerary in offer.get("itineraries", []):
				for segment in itinerary.get("segments", []):
					segment_origin = segment["departure"]["iataCode"]
					segment_destination = segment["arrival"]["iataCode"]

					# Check if the flight matches the filters
					if segment_origin == origin and segment_destination == destination:
						filtered_flights.append({
							"Flight ID": offer["id"],
							"Price (EUR)": float(offer["price"]["total"]),
							"Departure Time": segment["departure"]["at"],
							"Arrival Time": segment["arrival"]["at"],
						})

		return filtered_flights

	def calculate_average_price(self, flights):
		"""
		Calculate the average price of a list of flights.
		"""
		prices = [flight["Price (EUR)"] for flight in flights]
		return sum(prices) / len(prices) if prices else 0

	def save_to_excel(self, filtered_flights, filename):
		"""
		Save filtered flights to an Excel file.
		"""
		with pd.ExcelWriter(filename, engine="openpyxl") as writer:
			if filtered_flights:
				flights_df = pd.DataFrame(filtered_flights)
				flights_df.to_excel(writer, sheet_name="Flights", index=False)
				print(f"Filtered flights saved to {filename}")
			else:
				print("No flights found.")


# Usage Example
if __name__ == "__main__":
	# Replace these with your Amadeus API credentials
	api_key = "uxDqIh36xPAUvpXnXynwAnH86pGBdIch"
	api_secret = "xTSLooNZpJWantb5"

	# Initialize the FlightFilter
	flight_filter = FlightFilter(api_key, api_secret)

	# Request body for the API call
	request_body = {
		"currencyCode": "EUR",
		"originDestinations": [
			{
				"id": "1",
				"originLocationCode": "OPO",
				"destinationLocationCode": "CPH",
				"departureDateTimeRange": {"date": "2025-03-03", "time": "06:00:00"},
			},
			{
				"id": "2",
				"originLocationCode": "CPH",
				"destinationLocationCode": "OPO",
				"departureDateTimeRange": {"date": "2025-03-06", "time": "20:30:00"},
			},
		],
		"travelers": [{"id": "1", "travelerType": "ADULT"}],
		"sources": ["GDS"],
	}

	# Fetch flight offers
	flights = flight_filter.get_flight_offers(request_body)
	print(flights)

	# Filter flights by origin and destination
	opo_to_cph_flights = flight_filter.filter_flights(flights, "OPO", "CPH")
	cph_to_opo_flights = flight_filter.filter_flights(flights, "CPH", "OPO")

	# Calculate average prices
	avg_opo_to_cph_price = flight_filter.calculate_average_price(opo_to_cph_flights)
	avg_cph_to_opo_price = flight_filter.calculate_average_price(cph_to_opo_flights)

	# Output results
	print("Flights (OPO → CPH):", opo_to_cph_flights)
	print("Flights (CPH → OPO):", cph_to_opo_flights)
	print(f"Average OPO → CPH Price: {avg_opo_to_cph_price} EUR")
	print(f"Average CPH → OPO Price: {avg_cph_to_opo_price} EUR")

	# Save to Excel
	all_flights = opo_to_cph_flights + cph_to_opo_flights
	flight_filter.save_to_excel(all_flights, "Filtered_Flights.xlsx")
