#!/bin/bash

# Simple Amadeus API Test
# Tests: Authentication → Flight Search

echo "=========================================="
echo "Amadeus API Integration Test"
echo "=========================================="
echo ""

# Read credentials from .env file
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | grep 'AMADEUS_API' | xargs)
else
    echo "❌ Error: .env file not found"
    exit 1
fi

echo "Step 1: Getting Access Token..."
TOKEN_RESPONSE=$(curl -s -X POST \
  "$AMADEUS_API_BASE_URL/v1/security/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=$AMADEUS_API_KEY&client_secret=$AMADEUS_API_SECRET")

ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null)

if [ -z "$ACCESS_TOKEN" ]; then
    echo "❌ Failed to get access token"
    echo "$TOKEN_RESPONSE"
    exit 1
fi

echo "✅ Access Token: ${ACCESS_TOKEN:0:20}..."
echo ""

echo "Step 2: Searching for Flights (MAD → JFK, 2026-03-15)..."
SEARCH_RESPONSE=$(curl -s -X GET \
  "$AMADEUS_API_BASE_URL/v2/shopping/flight-offers?originLocationCode=MAD&destinationLocationCode=JFK&departureDate=2026-03-15&adults=1&max=3" \
  -H "Authorization: Bearer $ACCESS_TOKEN")

echo "$SEARCH_RESPONSE" | python3 -c "
import sys, json

try:
    data = json.load(sys.stdin)
    
    if 'errors' in data:
        print('❌ Error:', data['errors'][0]['detail'])
        sys.exit(1)
    
    if 'data' not in data or len(data['data']) == 0:
        print('⚠️  No flights found')
        sys.exit(0)
    
    print(f'✅ Found {len(data[\"data\"])} flight offers')
    print('')
    
    for i, offer in enumerate(data['data'][:3], 1):
        price = offer['price']['total']
        currency = offer['price']['currency']
        segments = offer['itineraries'][0]['segments']
        
        print(f'Flight {i}:')
        print(f'  Price: {price} {currency}')
        print(f'  Segments: {len(segments)}')
        
        for seg in segments:
            dep = seg['departure']
            arr = seg['arrival']
            print(f'    {dep[\"iataCode\"]} → {arr[\"iataCode\"]} | {seg[\"carrierCode\"]}{seg[\"number\"]}')
        print('')
    
    print('✅ Flight search successful!')
    
except Exception as e:
    print(f'❌ Error parsing response: {e}')
    sys.exit(1)
"

echo ""
echo "=========================================="
echo "Test Complete"
echo "=========================================="
