#!/usr/bin/env python3
"""
Primero obtenemos trenes reales de departures, y luego probamos onePaths con esos números
"""

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

ACCESS_KEY = "and20210615"
SECRET_KEY = "Jthjtr946RTt"

auth = AdifAuthenticator(access_key=ACCESS_KEY, secret_key=SECRET_KEY)

# Paso 1: Obtener trenes reales de departures
print("="*70)
print("PASO 1: Obteniendo trenes reales de Madrid Atocha")
print("="*70)

url = "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpaths/departures/traffictype/"
payload = {
    "commercialService": "BOTH",
    "commercialStopType": "BOTH",
    "page": {"pageNumber": 0},
    "stationCode": "10200",  # Madrid Atocha
    "trafficType": "AVLDMD"  # Alta Velocidad
}

user_id = str(uuid.uuid4())
headers = auth.get_auth_headers("POST", url, payload, user_id=user_id)
headers["User-key"] = auth.USER_KEY_CIRCULATION

response = requests.post(url, json=payload, headers=headers, timeout=10)

if response.status_code != 200:
    print(f"❌ Error obteniendo departures: {response.status_code}")
    print(response.text)
    exit(1)

data = response.json()
trains = data.get('circulations', [])

print(f"✅ Obtenidos {len(trains)} trenes\n")

# Mostrar los primeros 5 trenes
print("Primeros 5 trenes:")
for i, train in enumerate(trains[:5]):
    commercial_number = train.get('commercialNumber')
    destination = train.get('destination', {})
    dest_name = destination.get('longName', 'Unknown')
    origin = train.get('origin', {})
    origin_name = origin.get('longName', 'Unknown')
    planned_time = train.get('plannedTime', 'Unknown')

    print(f"\n{i+1}. Tren {commercial_number}")
    print(f"   Origen: {origin_name}")
    print(f"   Destino: {dest_name}")
    print(f"   Hora salida: {planned_time}")

# Paso 2: Probar onePaths con trenes reales
print("\n" + "="*70)
print("PASO 2: Probando onePaths con trenes reales")
print("="*70)

for i, train in enumerate(trains[:3]):  # Probar los primeros 3
    commercial_number = train.get('commercialNumber')
    destination = train.get('destination', {})
    dest_code = destination.get('stationCode')
    origin = train.get('origin', {})
    origin_code = origin.get('stationCode')

    # Obtener launchingDate del tren
    planned_time_str = train.get('plannedTime', '')
    # El plannedTime es algo como "08:30" - necesitamos convertirlo a timestamp
    now = datetime.now()
    today_start = int(datetime(now.year, now.month, now.day).timestamp() * 1000)

    print(f"\n{'='*70}")
    print(f"Test {i+1}: Tren {commercial_number}")
    print(f"{'='*70}")

    url_onepaths = "https://circulacion.api.adif.es/portroyalmanager/secure/circulationpathdetails/onepaths/"
    payload_onepaths = {
        "allControlPoints": True,
        "commercialNumber": commercial_number,
        "destinationStationCode": dest_code,
        "launchingDate": today_start,
        "originStationCode": origin_code
    }

    print(f"Payload: {json.dumps(payload_onepaths, indent=2)}")

    user_id = str(uuid.uuid4())
    headers = auth.get_auth_headers("POST", url_onepaths, payload_onepaths, user_id=user_id)
    headers["User-key"] = auth.USER_KEY_CIRCULATION

    response = requests.post(url_onepaths, json=payload_onepaths, headers=headers, timeout=10)

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

    if response.status_code == 200:
        print("✅ SUCCESS!")
        try:
            data = response.json()
            print(f"Response: {json.dumps(data, indent=2, ensure_ascii=False)[:2000]}")
        except:
            print(f"Response text: {response.text[:500]}")
    elif response.status_code == 204:
        print("⚠️ 204 No Content - Autenticación correcta pero sin datos")
    else:
        print(f"❌ FAILED - Status {response.status_code}")
        try:
            print(f"Error: {response.json()}")
        except:
            print(f"Response text: {response.text}")

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