"""Tests para compute_centers_reachability_pipeline.

Usa 2 orígenes y 2 centros reales en España con el stack Valhalla activo.
"""

from __future__ import annotations

import asyncio
import math
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", ".."))

from python.functions.pipelines.compute_centers_reachability_pipeline import (
    compute_centers_reachability_pipeline,
)


def test_compute_centers_reachability_pipeline():
    """Matrix 2×2 y 2 isócronas con Valhalla en localhost:8002."""
    origins = [
        (40.4168, -3.7038),   # Madrid
        (37.3891, -5.9845),   # Sevilla
    ]
    centers = [
        (41.3851, 2.1734),    # Barcelona
        (43.2627, -2.9253),   # Bilbao
    ]

    result = asyncio.run(
        compute_centers_reachability_pipeline(
            origins=origins,
            centers=centers,
            isochrone_minutes=15,
            base_url="http://localhost:8002",
            concurrency=4,
        )
    )

    assert isinstance(result, dict)
    assert "matrix" in result
    assert "isochrones" in result

    # Matrix: 2 orígenes × 2 centros = 4 entradas
    matrix = result["matrix"]
    assert len(matrix) == 4, f"Esperadas 4 entradas en matrix, got {len(matrix)}"

    for entry in matrix:
        assert "i" in entry and "j" in entry
        assert "meters" in entry and "seconds" in entry and "error" in entry
        # Si Valhalla resolvió el par, meters > 0
        if entry["error"] == 0:
            assert entry["meters"] > 0, "meters debe ser > 0 cuando no hay error"

    # Isochrones: 2 centros → 2 entradas
    isochrones = result["isochrones"]
    assert len(isochrones) == 2, f"Esperadas 2 isócronas, got {len(isochrones)}"

    # Al menos una isócrona debe ser un dict GeoJSON válido
    valid_isos = [iso for iso in isochrones if isinstance(iso, dict)]
    assert len(valid_isos) >= 1, "Al menos una isócrona debe ser un dict GeoJSON"
