# debug_opensky.py
import time
from datetime import datetime, timezone, timedelta
from opensky_api import OpenSkyApi
import requests  # Importiamo la libreria requests
import json

def run_historical_test():
    """
    Performs an isolated test of the OpenSky Network historical API call,
    first with a direct HTTP request, then with the library.
    """
    print("--- OpenSky Historical API Debug Script (Direct + Library) ---")

    # 1. Definisci i parametri ESATTI del test
    bbox_to_test = {
        "lamin": 44.986,
        "lomin": 7.9341,
        "lamax": 46.9567,
        "lomax": 10.5997,
    }
    
    now_utc = datetime.now(timezone.utc)
    timestamp_to_test = int((now_utc - timedelta(hours=2)).timestamp())
    
    # URL dell'endpoint REST per i dati storici
    # Nota: NON usiamo l'autenticazione per questo test, per replicare il comportamento anonimo
    opensky_url = f"https://opensky-network.org/api/states/all?time={timestamp_to_test}&lamin={bbox_to_test['lamin']}&lomin={bbox_to_test['lomin']}&lamax={bbox_to_test['lamax']}&lomax={bbox_to_test['lomax']}"

    print("1. Parameters for the test:")
    print(f"   - Bounding Box: {bbox_to_test}")
    print(f"   - Timestamp UTC (2 hours ago): {timestamp_to_test}")
    print(f"   - Direct API URL to be called: {opensky_url}\n")
    
    # --- TEST 1: Chiamata HTTP Diretta ---
    print("--- Test 1: Direct HTTP Request using 'requests' ---")
    try:
        print("2. Making direct HTTP GET request...")
        response = requests.get(opensky_url, timeout=15)
        print(f"   - Request completed. HTTP Status Code: {response.status_code}")

        # Controlla se la richiesta ha avuto successo (codice 2xx)
        if response.ok:
            # Prova a decodificare la risposta JSON
            try:
                data = response.json()
                print("   - Response content is valid JSON.")
                
                # Analizza il contenuto del JSON
                if data and "states" in data:
                    if data["states"]:
                        num_flights = len(data["states"])
                        print(f"   - SUCCESS: Found {num_flights} flight states in the direct response!")
                    else:
                        print("   - WARNING: Direct response contains an empty 'states' list. No flights found for this time/area.")
                else:
                    print("   - WARNING: Direct response JSON does not contain a 'states' key or is empty.")
                    print(f"     Raw JSON content: {data}")

            except json.JSONDecodeError:
                print("   - FAILURE: The server responded with OK, but the content is NOT valid JSON.")
                print(f"     Raw content (first 200 chars): {response.text[:200]}")
        else:
            print(f"   - FAILURE: The server responded with an error status code.")
            print(f"     Response content: {response.text}")

    except requests.exceptions.RequestException as e:
        print(f"\n   --- AN EXCEPTION OCCURRED DURING THE DIRECT HTTP CALL ---")
        print(f"   Error Type: {type(e).__name__}")
        print(f"   Error Details: {e}")

    # --- TEST 2: Chiamata tramite Libreria (per confronto) ---
    print("\n--- Test 2: Library Call using 'opensky-api' (for comparison) ---")
    try:
        api = OpenSkyApi()
        bbox_tuple = (bbox_to_test['lamin'], bbox_to_test['lamax'], bbox_to_test['lomin'], bbox_to_test['lomax'])
        states_response = api.get_states(time_secs=timestamp_to_test, bbox=bbox_tuple)
        
        if states_response:
             if states_response.states:
                 print(f"   - SUCCESS (Library): Found {len(states_response.states)} flights.")
             else:
                 print("   - WARNING (Library): Responded but 'states' list is empty.")
        else:
            print("   - FAILURE (Library): The API call returned a None object.")
    except Exception as e:
        print(f"   - EXCEPTION (Library): {e}")


if __name__ == "__main__":
    run_historical_test()