"""Markdown block implementation."""

from __future__ import annotations

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


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

    def __init__(self, block_id: str):
        super().__init__(block_id, "markdown")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        return False

    def append(self, content: str) -> None:
        """Append a new chunk to this markdown block."""
        event = self._create_chunk_event(
            data=MarkdownData(content=content),
        )
        push_output(event)

    def new_line(self, content: str) -> None:
        """Append a new line to this markdown block."""
        new_line_content = "\n\n" + content
        self.append(new_line_content)


class _MarkdownBlockFactory(_BlockFactory):
    """Factory for markdown blocks."""

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

    def __call__(self, content: str | None = None) -> MarkdownStream:
        """Create a markdown block or return a stream for context manager usage.

        Args:
            content: If provided, immediately emits a single markdown chunk.

        Returns:
            A MarkdownStream that can be used as a context manager for streaming
            additional chunks.

        """
        block_id = self._generate_block_id()

        stream = MarkdownStream(block_id)

        if content is not None:
            # Direct call or initial content for a stream: emit first chunk immediately
            stream.append(content)

        # Always return the stream, even if used only for a single chunk
        return stream


# Create the markdown callable/context manager
markdown = _MarkdownBlockFactory()

__all__ = ["markdown"]
