#!/usr/bin/env python3
"""
Script para probar diferentes endpoints de la API de Adif
"""

import sys
from pathlib import Path
# Agregar raíz del proyecto al path para importar adif_auth
sys.path.insert(0, str(Path(__file__).parent.parent))

import requests
import json
from datetime import datetime

# Headers descubiertos
HEADERS_CIRCULATION = {
    "Content-Type": "application/json;charset=utf-8",
    "User-key": "f4ce9fbfa9d721e39b8984805901b5df"
}

HEADERS_STATIONS = {
    "Content-Type": "application/json;charset=utf-8",
    "User-key": "0d021447a2fd2ac64553674d5a0c1a6f"
}

HEADERS_AVISA = {
    "Content-Type": "application/json;charset=utf-8",
    "Authorization": "Basic YXZpc3RhX2NsaWVudF9hbmRyb2lkOjh5WzZKNyFmSjwhXypmYXE1NyNnOSohNElwa2MjWC1BTg=="
}

# URLs base
BASE_CIRCULATION = "https://circulacion.api.adif.es"
BASE_STATIONS = "https://estaciones.api.adif.es"
BASE_AVISA = "https://avisa.adif.es"


def test_endpoint(name, method, url, headers, data=None):
    """Probar un endpoint y mostrar resultado"""
    print(f"\n{'='*60}")
    print(f"TEST: {name}")
    print(f"{'='*60}")
    print(f"Method: {method}")
    print(f"URL: {url}")
    print(f"Headers: {json.dumps(headers, indent=2)}")

    if data:
        print(f"Body: {json.dumps(data, indent=2)}")

    try:
        if method == "GET":
            response = requests.get(url, headers=headers, timeout=10)
        elif method == "POST":
            response = requests.post(url, headers=headers, json=data, timeout=10)
        else:
            print(f"❌ Método {method} no soportado")
            return

        print(f"\nStatus: {response.status_code}")

        if response.status_code == 200:
            print("✅ SUCCESS")
            result = response.json()
            print(f"\nResponse Preview:")
            print(json.dumps(result, indent=2, ensure_ascii=False)[:1000] + "...")
        else:
            print(f"❌ ERROR")
            print(f"Response: {response.text[:500]}")

    except Exception as e:
        print(f"❌ EXCEPTION: {str(e)}")


def main():
    print("=" * 60)
    print("PRUEBAS DE ENDPOINTS DE ADIF API")
    print("=" * 60)

    # Test 1: Obtener salidas con diferentes formatos de body
    test_endpoint(
        "Salidas - Formato Simple",
        "POST",
        f"{BASE_CIRCULATION}/portroyalmanager/secure/circulationpaths/departures/traffictype/",
        HEADERS_CIRCULATION,
        {
            "stationCode": "10200",
            "commercialService": "BOTH",
            "commercialStopType": "BOTH",
            "page": {"pageNumber": 0},
            "trafficType": "CERCANIAS"
        }
    )

    # Test 2: Probar con State YES
    test_endpoint(
        "Salidas - State YES",
        "POST",
        f"{BASE_CIRCULATION}/portroyalmanager/secure/circulationpaths/departures/traffictype/",
        HEADERS_CIRCULATION,
        {
            "stationCode": "10200",
            "commercialService": "YES",
            "commercialStopType": "YES",
            "page": {"pageNumber": 0},
            "trafficType": "ALL"
        }
    )

    # Test 3: Detalles de una ruta específica
    test_endpoint(
        "Detalles de Ruta",
        "POST",
        f"{BASE_CIRCULATION}/portroyalmanager/secure/circulationpathdetails/onepaths/",
        HEADERS_CIRCULATION,
        {
            "commercialNumber": "C1",
            "allControlPoints": False
        }
    )

    # Test 4: Entre estaciones
    test_endpoint(
        "Entre Estaciones",
        "POST",
        f"{BASE_CIRCULATION}/portroyalmanager/secure/circulationpaths/betweenstations/traffictype/",
        HEADERS_CIRCULATION,
        {
            "originStationCode": "10200",
            "destinationStationCode": "10302",
            "commercialService": "BOTH",
            "commercialStopType": "BOTH",
            "page": {"pageNumber": 0},
            "trafficType": "ALL"
        }
    )

    # Test 5: Detalles de estación
    test_endpoint(
        "Detalles de Estación",
        "POST",
        f"{BASE_STATIONS}/portroyalmanager/secure/stations/onestation/",
        HEADERS_STATIONS,
        {
            "stationCode": "10200"
        }
    )

    # Test 6: Observaciones de estación
    test_endpoint(
        "Observaciones de Estación",
        "POST",
        f"{BASE_STATIONS}/portroyalmanager/secure/stationsobservations/",
        HEADERS_STATIONS,
        {
            "stationCode": "10200"
        }
    )

    # Test 7: Composición de tren
    test_endpoint(
        "Composición de Tren",
        "POST",
        f"{BASE_CIRCULATION}/portroyalmanager/secure/circulationpaths/compositions/path/",
        HEADERS_CIRCULATION,
        {
            "commercialNumber": "AVE 1001",
            "originStationCode": "10200",
            "destinationStationCode": "71801"
        }
    )

    print("\n" + "="*60)
    print("RESUMEN")
    print("="*60)
    print("""
Las pruebas han finalizado. Revisa los resultados arriba.

NOTAS:
- Algunos endpoints pueden requerir códigos/números válidos
- Los códigos de estación son numéricos (ej: 10200 para Madrid Atocha)
- Los números comerciales varían según el tipo de tren
- Algunos datos pueden no estar disponibles en tiempo real

CÓDIGOS DE ESTACIÓN COMUNES:
- 10200: Madrid Puerta de Atocha
- 10302: Madrid Chamartín
- 71801: Barcelona Sants
- 50000: Valencia Nord
- 11401: Sevilla Santa Justa

TIPOS DE TRÁFICO:
- CERCANIAS: Trenes de cercanías
- MEDIA_DISTANCIA: Media distancia
- LARGA_DISTANCIA: Larga distancia
- ALL: Todos los tipos

ESTADOS:
- YES: Solo servicios/paradas comerciales
- NOT: Sin servicios/paradas comerciales
- BOTH: Ambos tipos
""")


if __name__ == "__main__":
    main()
