from __future__ import annotations

from collections.abc import Iterable

from fastapi import APIRouter

from src.api.v1.platform import router


def _get_paths_for_method(api_router: APIRouter, method: str) -> list[str]:
    paths: list[str] = []

    for route in api_router.routes:
        nested_router = getattr(route, "original_router", None)
        if isinstance(nested_router, APIRouter):
            paths.extend(_get_paths_for_method(nested_router, method))
            continue

        methods: Iterable[str] = getattr(route, "methods", set())
        if method in methods:
            paths.append(getattr(route, "path"))

    return paths


def test_runs_list_route_is_registered_before_dynamic_run_id() -> None:
    paths = _get_paths_for_method(router, "GET")

    assert "/runs/list" in paths
    assert "/runs/{run_id}/detail" in paths
    assert "/runs/{run_id}" in paths
    assert paths.index("/runs/list") < paths.index("/runs/{run_id}")
    assert paths.index("/runs/{run_id}/detail") < paths.index("/runs/{run_id}")


def test_recent_events_route_is_registered() -> None:
    paths = _get_paths_for_method(router, "GET")

    assert "/events/recent" in paths


def test_truth_chain_route_is_registered() -> None:
    paths = _get_paths_for_method(router, "GET")

    assert "/truth-chain/{source_id}" in paths


def test_truth_chain_quality_summary_route_is_registered_before_dynamic_source_id() -> None:
    paths = _get_paths_for_method(router, "GET")

    assert "/truth-chain/quality/summary" in paths
    assert "/truth-chain/{source_id}" in paths
    assert paths.index("/truth-chain/quality/summary") < paths.index("/truth-chain/{source_id}")
