"""Action block implementation."""

from __future__ import annotations

from yera.events.blocks.base import _BlockFactory, _StreamHandle
from yera.events.models import ActionData
from yera.events.stream import push_output


class ActionStream(_StreamHandle):
    """Stream handle for creating multiple chunks of the same action block."""

    def __init__(self, block_id: str, initial_message: str):
        super().__init__(block_id, "action")
        self.initial_message = initial_message

    def __enter__(self):
        event = self._create_chunk_event(
            data=ActionData(status="active", message=self.initial_message),
        )
        push_output(event)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        event = self._create_chunk_event(
            data=ActionData(status="complete"),
        )
        push_output(event)
        return False

    def update(self, message: str) -> None:
        """Create an update chunk with status 'active'."""
        event = self._create_chunk_event(
            data=ActionData(status="active", message=message),
        )
        push_output(event)


class _ActionBlockFactory(_BlockFactory):
    """Factory for action blocks. Returns a context manager when called with message."""

    def __init__(self):
        super().__init__("action")

    def __call__(
        self,
        message: str,
    ) -> ActionStream:
        """Return a context manager for creating multiple action chunks."""
        block_id = self._generate_block_id()
        return ActionStream(block_id, message)


# Create the action callable/context manager
action = _ActionBlockFactory()

__all__ = ["action"]
