from backend.scripts.stations_import import (
    build_overpass_query,
    normalize_station_elements,
)


def test_build_overpass_query_single_region() -> None:
    query = build_overpass_query("berlin_metropolitan")

    # The query should reference the Berlin bounding box coordinates.
    assert "52.3381" in query  # south
    assert "52.6755" in query  # north
    assert "13.0884" in query  # west
    assert "13.7611" in query  # east
    assert "node" in query
    assert "out body" in query


def test_build_overpass_query_all_regions_includes_union() -> None:
    query = build_overpass_query("all")

    # Ensure multiple regions are present by checking for repeated bbox parentheses.
    assert query.count("node") >= 3
    assert query.strip().endswith("out skel qt;")


def test_normalize_station_elements_filters_and_transforms() -> None:
    raw_elements = [
        {
            "type": "node",
            "id": 123,
            "lat": 52.5,
            "lon": 13.4,
            "tags": {
                "name": "Sample Station",
                "ref": "XYZ",
                "ele": "35.5",
            },
        },
        {
            "type": "node",
            "id": 999,
            # Missing coordinates should be ignored
            "tags": {"name": "Broken"},
        },
        {
            "type": "node",
            "id": 456,
            "lat": 50.0,
            "lon": 8.0,
            "tags": {
                "name": "Disused Station",
                "disused": "yes",
            },
        },
    ]

    stations = normalize_station_elements(raw_elements)

    assert len(stations) == 2
    primary = stations[0]
    assert primary["osm_id"] == "123"
    assert primary["name"] == "Sample Station"
    assert primary["code"] == "XYZ"
    assert primary["elevation_m"] == 35.5
    disused_station = stations[1]
    assert disused_station["is_active"] is False
