"""Template block model."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from better_notion._sdk.models.block import Block

if TYPE_CHECKING:
    from better_notion._sdk.client import NotionClient


class Template(Block):
    """Template block (reusable block template).

    Example:
        >>> template = await Template.create(
        ...     parent=page,
        ...     client=client,
        ...     text="Meeting Notes"
        ... )
    """

    def __init__(self, client: "NotionClient", data: dict[str, Any]) -> None:
        """Initialize a Template block.

        Args:
            client: NotionClient instance
            data: Raw block data from Notion API
        """
        super().__init__(client, data)

    @property
    def text(self) -> str:
        """Get template text.

        Returns:
            Template text
        """
        template_data = self._data.get("template", {})
        text_array = template_data.get("rich_text", [])
        if text_array and text_array[0].get("type") == "text":
            return text_array[0]["text"].get("content", "")
        return ""

    @classmethod
    async def create(
        cls,
        parent: "Page | Block",
        *,
        client: "NotionClient",
        text: str,
        **kwargs: Any
    ) -> "Template":
        """Create a new template block.

        Args:
            parent: Parent page or block
            client: NotionClient instance
            text: Template text
            **kwargs: Additional parameters

        Returns:
            Newly created Template block

        Example:
            >>> template = await Template.create(
            ...     parent=page,
            ...     client=client,
            ...     text="Meeting Notes"
            ... )
        """
        from better_notion._api.properties import RichText

        # Prepare parent reference
        if hasattr(parent, 'id'):
            parent_id = parent.id
        else:
            raise ValueError("Parent must be a Page or Block object")

        # Build template data
        template_data = {
            "rich_text": [RichText[text]]
        }

        # Build template block data
        block_data = {
            "type": "template",
            "template": template_data
        }

        # Create block via API
        data = await client.api.blocks.children.append(
            block_id=parent_id,
            children=[block_data]
        )

        # Return first created block
        result_data = data.get("results", [{}])[0]
        return cls.from_data(client, result_data)

    def __repr__(self) -> str:
        """String representation."""
        text_preview = self.text[:30] if self.text else ""
        return f"Template({text_preview!r})"
