from __future__ import annotations

import httpx
import pytest
import respx

from omni.client.async_client import AsyncOmniClient


def _config(url: str = "https://omni.example") -> dict:
    return {
        "default_instance": "default",
        "instances": {
            "default": {
                "url": url,
            }
        },
    }


@pytest.mark.asyncio()
async def test_retry_on_idempotent_get() -> None:
    with respx.mock(base_url="https://omni.example") as mock:
        route = mock.post("/api/omni.resources.ResourceService/Get")
        route.side_effect = [
            httpx.Response(503, json={"error": "unavailable"}),
            httpx.Response(200, json={"body": '{"metadata":{"id":"x"}}'}),
        ]

        client = AsyncOmniClient(config=_config())
        payload = await client.resources.get(
            {"namespace": "default", "type": "Clusters.omni.sidero.dev", "id": "x"}
        )

        assert "body" in payload
        assert route.call_count == 2
        assert route.calls.last is not None
        assert route.calls.last.request.headers["Grpc-Metadata-runtime"] == "Omni"
        await client.aclose()
