from typing import Optional
from typing import List
from typing import Dict
from typing import Any
import asyncio


async def _wait_build_state(
    client, build_id, desired_phase: Optional[str], desired_states: List[str]
) -> Dict[str, Any]:
    """ Wait until the build is in one of the desired states, or in the desired phase. """
    while True:
        resp = client.batch_get_builds(ids=[build_id])
        assert len(resp["builds"]) == 1
        build = resp["builds"][0]
        if build["buildStatus"] in desired_states:
            return build
        for phase in build["phases"]:
            if desired_phase and (phase["phaseType"] == desired_phase):
                return build

        await asyncio.sleep(2)