#!/usr/bin/env python3
"""
Prueba detallada de endpoints con mensajes de error completos
"""

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
from adif_auth import AdifAuthenticator
import uuid
import json
from datetime import datetime, timedelta
import time

ACCESS_KEY = "and20210615"
SECRET_KEY = "Jthjtr946RTt"

def test_endpoint_detailed(name, url, payload, use_stations_key=False):
    """
    Prueba un endpoint y muestra información detallada
    """
    auth = AdifAuthenticator(access_key=ACCESS_KEY, secret_key=SECRET_KEY)
    user_id = str(uuid.uuid4())

    headers = auth.get_auth_headers("POST", url, payload, user_id=user_id)
    if use_stations_key:
        headers["User-key"] = auth.USER_KEY_STATIONS
    else:
        headers["User-key"] = auth.USER_KEY_CIRCULATION

    print(f"\n{'='*70}")
    print(f"Testing: {name}")
    print(f"{'='*70}")
    print(f"URL: {url}")
    print(f"Payload: {json.dumps(payload, indent=2)}")

    try:
        response = requests.post(url, json=payload, headers=headers, timeout=10)
        print(f"\nStatus Code: {response.status_code}")
        print(f"Headers: {dict(response.headers)}")

        try:
            response_json = response.json()
            print(f"Response Body: {json.dumps(response_json, indent=2, ensure_ascii=False)[:1000]}")
        except:
            print(f"Response Body (text): {response.text[:500]}")

        if response.status_code == 200:
            print("✅ SUCCESS")
            return True
        else:
            print(f"❌ FAILED - Status {response.status_code}")
            return False

    except Exception as e:
        print(f"❌ ERROR: {e}")
        return False

# Obtener timestamps
now = datetime.now()
# Fecha actual al inicio del día en milisegundos
today_start = int(datetime(now.year, now.month, now.day).timestamp() * 1000)
# Fecha de mañana al inicio del día
tomorrow_start = int((datetime(now.year, now.month, now.day) + timedelta(days=1)).timestamp() * 1000)

print(f"Testing con fechas:")
print(f"Today (start): {today_start} = {datetime.fromtimestamp(today_start/1000)}")
print(f"Tomorrow (start): {tomorrow_start} = {datetime.fromtimestamp(tomorrow_start/1000)}")

# Test betweenStations (401)
test_endpoint_detailed(
    "BetweenStations",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpaths/betweenstations/traffictype/",
    {
        "commercialService": "BOTH",
        "commercialStopType": "BOTH",
        "originStationCode": "10200",
        "destinationStationCode": "71801",
        "page": {"pageNumber": 0},
        "trafficType": "ALL"
    }
)

# Test onePaths con variaciones (400)
print("\n\n" + "="*70)
print("TESTING ONEPATHS CON DIFERENTES VARIACIONES")
print("="*70)

# Variación 1: Con commercialNumber válido
test_endpoint_detailed(
    "OnePaths - Con commercialNumber '03194'",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/",
    {
        "allControlPoints": True,
        "commercialNumber": "03194",
        "destinationStationCode": "71801",
        "launchingDate": today_start,
        "originStationCode": "10200"
    }
)

# Variación 2: Sin commercialNumber
test_endpoint_detailed(
    "OnePaths - Sin commercialNumber (null)",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/",
    {
        "allControlPoints": True,
        "commercialNumber": None,
        "destinationStationCode": "71801",
        "launchingDate": today_start,
        "originStationCode": "10200"
    }
)

# Variación 3: Sin el campo commercialNumber completamente
test_endpoint_detailed(
    "OnePaths - Sin campo commercialNumber",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/",
    {
        "allControlPoints": True,
        "destinationStationCode": "71801",
        "launchingDate": today_start,
        "originStationCode": "10200"
    }
)

# Variación 4: Solo con originStationCode (sin destination)
test_endpoint_detailed(
    "OnePaths - Solo originStationCode",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/",
    {
        "allControlPoints": True,
        "launchingDate": today_start,
        "originStationCode": "10200"
    }
)

# Variación 5: Estructura mínima
test_endpoint_detailed(
    "OnePaths - Estructura mínima",
    "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/",
    {
        "commercialNumber": "03194",
        "launchingDate": today_start
    }
)

# Test OneStation con onestation (401)
test_endpoint_detailed(
    "OneStation",
    "https://estaciones.api.adif.es/portroyalmanager/secure/stations/onestation/",
    {
        "stationCode": "10200",
        "detailedInfo": {
            "extendedStationInfo": True,
            "stationActivities": True,
            "stationBanner": True,
            "stationCommercialServices": True,
            "stationInfo": True,
            "stationServices": True,
            "stationTransportServices": True
        }
    },
    use_stations_key=True
)

# Variación: OneStation simple
test_endpoint_detailed(
    "OneStation - Simple",
    "https://estaciones.api.adif.es/portroyalmanager/secure/stations/onestation/",
    {
        "stationCode": "10200"
    },
    use_stations_key=True
)

print("\n" + "="*70)
print("PRUEBA COMPLETADA")
print("="*70)
