"""Run 状态转移表。"""
from __future__ import annotations

from typing import Dict, FrozenSet

from ..enums import RunState


class IllegalTransition(ValueError):
    pass


RUN_TRANSITIONS: Dict[RunState, FrozenSet[RunState]] = {
    RunState.QUEUED: frozenset({RunState.PREFLIGHT, RunState.ABORTED}),
    RunState.PREFLIGHT: frozenset(
        {RunState.RUNNING, RunState.REJECTED, RunState.ABORTED}
    ),
    RunState.RUNNING: frozenset(
        {
            RunState.RECOVERING,
            RunState.PAUSED,
            RunState.FROZEN,
            RunState.COMPLETED,
            RunState.ABORTED,
        }
    ),
    RunState.RECOVERING: frozenset(
        {RunState.RUNNING, RunState.FROZEN, RunState.ABORTED}
    ),
    RunState.PAUSED: frozenset({RunState.RUNNING, RunState.ABORTED}),
    RunState.FROZEN: frozenset(),
    RunState.COMPLETED: frozenset(),
    RunState.ABORTED: frozenset(),
    RunState.REJECTED: frozenset(),
}


def assert_run_transition(current: str, target: str) -> None:
    current_state = RunState(current)
    target_state = RunState(target)
    if target_state not in RUN_TRANSITIONS[current_state]:
        raise IllegalTransition(
            "Run 状态不允许从 {0} 转到 {1}".format(current_state.value, target_state.value)
        )
