from __future__ import annotations

from backend.scripts import tracks_import


def test_normalize_track_elements_excludes_invalid_geometries() -> None:
    elements = [
        {
            "type": "way",
            "id": 123,
            "geometry": [
                {"lat": 52.5, "lon": 13.4},
                {"lat": 52.6, "lon": 13.5},
            ],
            "tags": {
                "name": "Main Line",
                "railway": "rail",
                "maxspeed": "120",
            },
        },
        {
            "type": "way",
            "id": 456,
            "geometry": [
                {"lat": 51.0},
            ],
            "tags": {"railway": "rail"},
        },
        {
            "type": "node",
            "id": 789,
        },
    ]

    tracks = tracks_import.normalize_track_elements(elements)

    assert len(tracks) == 1
    track = tracks[0]
    assert track["osmId"] == "123"
    assert track["name"] == "Main Line"
    assert track["maxSpeedKph"] == 120.0
    assert track["status"] == "operational"
    assert track["isBidirectional"] is True
    assert track["coordinates"] == [[52.5, 13.4], [52.6, 13.5]]
    assert track["lengthMeters"] > 0


def test_normalize_track_elements_marks_oneway_and_status() -> None:
    elements = [
        {
            "type": "way",
            "id": 42,
            "geometry": [
                {"lat": 48.1, "lon": 11.5},
                {"lat": 48.2, "lon": 11.6},
            ],
            "tags": {
                "railway": "disused",
                "oneway": "yes",
            },
        }
    ]

    tracks = tracks_import.normalize_track_elements(elements)

    assert len(tracks) == 1
    track = tracks[0]
    assert track["status"] == "disused"
    assert track["isBidirectional"] is False


def test_normalize_track_elements_skips_service_tracks() -> None:
    elements = [
        {
            "type": "way",
            "id": 77,
            "geometry": [
                {"lat": 52.5000, "lon": 13.4000},
                {"lat": 52.5010, "lon": 13.4010},
            ],
            "tags": {
                "railway": "rail",
                "service": "yard",
            },
        }
    ]

    tracks = tracks_import.normalize_track_elements(elements)

    assert tracks == []


def test_normalize_track_elements_skips_short_tracks() -> None:
    elements = [
        {
            "type": "way",
            "id": 81,
            "geometry": [
                {"lat": 52.500000, "lon": 13.400000},
                {"lat": 52.500100, "lon": 13.400050},
            ],
            "tags": {
                "railway": "rail",
            },
        }
    ]

    tracks = tracks_import.normalize_track_elements(elements)

    assert tracks == []
