"""Tests para valhalla_matrix_1_to_n."""

from __future__ import annotations

import math
import sys
import os

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

import httpx
import pytest

from valhalla_matrix_1_to_n import valhalla_matrix_1_to_n


def _valhalla_alive(url: str = "http://localhost:8002") -> bool:
    try:
        r = httpx.get(f"{url}/status", timeout=2.0)
        return r.status_code < 500
    except Exception:
        return False


VALHALLA_OK = _valhalla_alive()
skip_if_no_valhalla = pytest.mark.skipif(
    not VALHALLA_OK, reason="Valhalla no activo en :8002"
)


@skip_if_no_valhalla
def test_matrix_1_origen_2_destinos_retorna_2_dicts_con_meters_mayor_0():
    """matrix 1 origen 2 destinos retorna 2 dicts con meters > 0"""
    origins = [(40.4168, -3.7038)]         # Madrid
    destinations = [
        (41.3874, 2.1686),                 # Barcelona
        (37.3886, -5.9823),                # Sevilla
    ]
    pairs = [(0, 0), (0, 1)]

    results = valhalla_matrix_1_to_n(origins, destinations, pairs)
    assert len(results) == 2, f"Esperaba 2 resultados, obtuvo {len(results)}"
    for i, r in enumerate(results):
        assert r["error"] == 0, f"Par {i} tiene error={r['error']}"
        assert r["meters"] > 0, f"Par {i} tiene meters={r['meters']}"
        assert not math.isnan(r["seconds"]), f"Par {i} tiene seconds=NaN"
