"""Poll a remote job until it reaches a terminal state."""

from __future__ import annotations

import asyncio
from collections.abc import Iterator
from typing import TypedDict

from infra_core import poll_until_async


class JobResponse(TypedDict):
    status: str
    result_url: str | None


async def main() -> None:
    states: Iterator[JobResponse] = iter(
        [
            {"status": "queued", "result_url": None},
            {"status": "running", "result_url": None},
            {"status": "succeeded", "result_url": "https://example.com/results/123"},
        ]
    )

    async def fetch_status() -> JobResponse:
        await asyncio.sleep(0.1)
        return next(states)

    def is_terminal(response: JobResponse) -> bool:
        return response["status"] in {"succeeded", "failed"}

    result: JobResponse = await poll_until_async(
        fetch_fn=fetch_status,
        is_terminal=is_terminal,
        timeout=30.0,
        poll_interval=0.25,
        backoff_multiplier=1.5,
    )
    print(result)


if __name__ == "__main__":
    asyncio.run(main())
