"""
Loop - Loop control block.
https://docs.aws.amazon.com/connect/latest/APIReference/flow-control-actions-loop.html
"""

from dataclasses import dataclass
from typing import Optional
import uuid
from ..base import FlowBlock


@dataclass
class Loop(FlowBlock):
    """
    Loop a specified number of times.

    Parameters:
        - LoopCount - Number of loops (0-100, static or dynamic)

    Results:
        - ContinueLooping - Loop should continue
        - DoneLooping - Loop should finish

    Errors:
        None.

    Restrictions:
        - Supported in all flow types
        - Supported on all channels
        - Must have conditions for both ContinueLooping and DoneLooping
    """

    loop_count: Optional[int] = None

    def __post_init__(self):
        self.type = "Loop"
        self._build_parameters()

    def _build_parameters(self):
        """Build parameters dict from typed attributes."""
        params = {}
        if self.loop_count is not None:
            params["LoopCount"] = str(self.loop_count)
        self.parameters = params

    def __repr__(self) -> str:
        return f"Loop(loop_count={self.loop_count})"

    def to_dict(self) -> dict:
        self._build_parameters()
        return super().to_dict()

    @classmethod
    def from_dict(cls, data: dict) -> "Loop":
        params = data.get("Parameters", {})
        loop_count_str = params.get("LoopCount")
        loop_count = int(loop_count_str) if loop_count_str else None
        return cls(
            identifier=data.get("Identifier", str(uuid.uuid4())),
            loop_count=loop_count,
            parameters=params,
            transitions=data.get("Transitions", {}),
        )
