from __future__ import annotations

from pydantic import BaseModel

from yera.events.blocks.base import _BlockFactory
from yera.events.models import ExitEventData
from yera.events.stream import push_output


class _ExitBlockFactory(_BlockFactory):
    def __init__(self):
        super().__init__("exit")

    def __call__(self, exit_code: int, reason: str | None, return_value: str | None):
        return_type = type(return_value).__name__

        if isinstance(return_value, BaseModel):
            return_value = return_value.model_dump_json()

        event = self._create_block_output_event(
            data=ExitEventData(
                exit_code=exit_code,
                reason=reason,
                return_type=return_type,
                return_value=str(return_value),
            ),
            message_type="informational",
        )
        push_output(event)


exit_event = _ExitBlockFactory()


def quit_event():
    exit_event(exit_code=0, reason="User quit", return_value=None)


__all__ = ["exit_event", "quit_event"]
