import json
from pprint import pprint
from amadeus import Client, ResponseError
import pandas as pd
from datetime import datetime, timedelta
from flight_types import *

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

	def get_flight_offers(self, request_body):
		"""
		Fetch flight offers using the Amadeus SDK with a JSON 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, Exception) as error:
			print(f"Error fetching flight offers: {error}")
			return []

	def filter_and_average_price(flights, morning_departure, evening_departure, morning_hours = 2, evening_hours = 2):
		"""
		Filters flights:
		- Morning departures from OPO.
		- Evening departures from CPH.
		- Calculates the average price of the matched trips.
		"""
		morning_time = datetime.strptime( morning_departure, "%H:%M" )
		evening_time = datetime.strptime( evening_departure, "%H:%M" )

		morning_start = morning_time - timedelta( hours = morning_hours )
		morning_end = morning_time + timedelta( hours = morning_hours )
		evening_start = evening_time - timedelta( hours = evening_hours )
		evening_end = evening_time + timedelta( hours = evening_hours )

		morning_flights = []
		evening_flights = []

		for offer in flights:
			for itinerary in offer.get( "itineraries", [] ):
				for segment in itinerary.get( "segments", [] ):
					departure_time = datetime.strptime( segment["departure"]["at"], "%Y-%m-%dT%H:%M:%S" )
					origin = segment["departure"]["iataCode"]
					destination = segment["arrival"]["iataCode"]

					# Morning flights from OPO
					if (
							origin == "OPO" and destination == "CPH"
							and morning_start.time() <= departure_time.time() <= morning_end.time()
					):
						morning_flights.append( {
							"Flight ID": offer["id"],
							"Price (EUR)": float( offer["price"]["total"] ),
							"Departure Time": segment["departure"]["at"],
							"Arrival Time": segment["arrival"]["at"],
						} )

					# Evening flights from CPH
					elif (
							origin == "CPH" and destination == "OPO"
							and evening_start.time() <= departure_time.time() <= evening_end.time()
					):
						evening_flights.append( {
							"Flight ID": offer["id"],
							"Price (EUR)": float( offer["price"]["total"] ),
							"Departure Time": segment["departure"]["at"],
							"Arrival Time": segment["arrival"]["at"],
						} )

		# Calculate average prices
		morning_prices = [flight["Price (EUR)"] for flight in morning_flights]
		evening_prices = [flight["Price (EUR)"] for flight in evening_flights]

		average_morning_price = sum( morning_prices ) / len( morning_prices ) if morning_prices else 0
		average_evening_price = sum( evening_prices ) / len( evening_prices ) if evening_prices else 0

		return {
			"Morning Flights": morning_flights,
			"Evening Flights": evening_flights,
			"Average Morning Price (EUR)": average_morning_price,
			"Average Evening Price (EUR)": average_evening_price,
		}

		return filtered_flights

	def save_to_excel(self, lis_flights, cph_flights, filename):
		"""Save flights from LIS and CPH into separate blocks in an Excel sheet."""
		with pd.ExcelWriter( filename, engine = "openpyxl" ) as writer:
			# Check for OPO → CPH flights
			if lis_flights:
				lis_df = pd.DataFrame( lis_flights )
				lis_df.sort_values( by = "Departure Time", inplace = True )
				lis_df.to_excel( writer, sheet_name = "Flights", startrow = 1, index = False )
				writer.sheets["Flights"].cell( row = 1, column = 1 ).value = "Departures from OPO around 07:00"
			else:
				print( "No flights found from OPO to CPH." )

			# Check for CPH → OPO flights
			if cph_flights:
				cph_df = pd.DataFrame( cph_flights )
				cph_df.sort_values( by = "Departure Time", inplace = True )
				cph_df.to_excel( writer, sheet_name = "Flights", startrow = len( lis_flights ) + 4, index = False )
				writer.sheets["Flights"].cell( row = len( lis_flights ) + 4,
				                               column = 1 ).value = "Departures from CPH around 18:30"
			else:
				print( "No flights found from CPH to OPO." )

			# If no data exists, add a placeholder sheet
			if not lis_flights and not cph_flights:
				print( "No flight data available. Adding placeholder sheet." )
				pd.DataFrame( { "Message": ["No flights found"] } ).to_excel( writer, sheet_name = "Flights",
				                                                              index = False )

		print( f"Filtered flights saved to: {filename}" )


# Usage example
if __name__ == "__main__":
	api_key = "uxDqIh36xPAUvpXnXynwAnH86pGBdIch"
	api_secret = "xTSLooNZpJWantb5"

	# PROD PROD PROD PROD PROD PROD PROD PROD PROD PROD
	#api_key = "ABRGQv6U7IWAYxwwmjqAOPUDGvuFMSjw"
	#api_secret = "BcwpSKf3FICJIxaw"

	flight_filter = FlightFilter(api_key, api_secret)

	# JSON request body
	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-03",
					"time": "20:30:00"
				}
			}
		],
		"travelers": [
			{"id": "1", "travelerType": "ADULT"}
		],
		"sources": ["GDS"],
	}

	# Fetch flights
	flights = flight_filter.get_flight_offers(request_body)
	#with open("json_data.json", "w") as file:
    #		json.dump(flights, file)
	#
	#DEBUG
	# with open("json_data.json", "r") as file:
	# 	flights = json.load(file)

	#print(f"Raw flights data: {flights}")

	real_flights = []

	for flight in flights:
		for x,v in flight.items():
			if type(v) == list and "itineraries" in str(x).lower():
				for flt, flt2 in flight.items():
					if flt == "itineraries":
						for itm in flt2:
							for seg in itm.get("segments"):
								departure = seg.get("departure").get("iataCode")
								arrival = seg.get("arrival").get("iataCode")
								print(f"{departure} -> {arrival}")
								if (departure, arrival) in (("OPO", "CPH"), ("CPH", "OPO")):
									print( f"-->> {departure} -> {arrival} <<--" )











	# Filter flights from OPO to CPH around 07:00 ± 1 hour
	#opo_to_cph_flights = flight_filter.filter_flights_by_time(
	#		flights, origin_filter="OPO", destination_filter="CPH", filter_time_str="06:00", hours=2
	#)

	# Filter flights from CPH to OPO around 18:30 ± 1 hour
	#cph_to_opo_flights = flight_filter.filter_flights_by_time(
    #		flights, origin_filter="CPH", destination_filter="OPO", filter_time_str="20:30", hours=2
	#)

	# Save to Excel
	#flight_filter.save_to_excel(opo_to_cph_flights, cph_to_opo_flights, "Filtered_Flights_OPO_CPH.xlsx")
