from typing import Any

from sinapsis_anthropic.helpers.anthropic_keys import AnthropicKeys
from sinapsis_anthropic.templates.anthropic_text_generation import AnthropicTextGeneration
from sinapsis_chatbots_base.helpers.llm_conversation import image_array_to_base64
from sinapsis_chatbots_base.helpers.tags import Tags
from sinapsis_chatbots_base.templates.llm_multimodal_base import LLMMultimodalTemplateBase
from sinapsis_core.data_containers.data_packet import DataContainer
from sinapsis_core.template_base.base_models import OutputTypes, UIPropertiesMetadata


class AnthropicMultiModal(LLMMultimodalTemplateBase, AnthropicTextGeneration):
    """Template for multimodal Anthropic chat processing.

    Usage example:

    agent:
      name: my_test_agent
    templates:
    - template_name: InputTemplate
      class_name: InputTemplate
      attributes: {}
    - template_name: AnthropicMultiModal
      class_name: AnthropicMultiModal
      template_input: LLMConversationInput
      attributes:
        init_args:
          llm_model_name: claude-sonnet-4-6
        completion_args:
          max_tokens: 1024
          temperature: 0.2
          service_tier: standard_only
        extended_thinking:
          type: disabled
        web_search: false
    """

    UIProperties = UIPropertiesMetadata(
        category="Anthropic",
        output_type=OutputTypes.TEXT,
        tags=[
            Tags.ANTHROPIC,
            Tags.CHATBOTS,
            Tags.CONTEXT,
            Tags.LLM,
            Tags.TEXT_COMPLETION,
            Tags.TEXT,
            Tags.MULTIMODAL,
            Tags.IMAGE_TO_TEXT,
        ],
    )

    @staticmethod
    def extract_additional_content(container: DataContainer) -> list[dict[str, Any]]:
        """Convert container images into Anthropic image content blocks.

        Args:
            container (DataContainer): Container holding image packets.

        Returns:
            list[dict[str, Any]]: Anthropic-compatible image content blocks.
        """
        return [
            {
                AnthropicKeys.type: AnthropicKeys.image,
                AnthropicKeys.source: {
                    AnthropicKeys.type: AnthropicKeys.base64,
                    AnthropicKeys.media_type: f"{AnthropicKeys.image}/{AnthropicKeys.jpeg}",
                    AnthropicKeys.data: image_array_to_base64(image.content),
                },
            }
            for image in container.images
        ]

    @staticmethod
    def build_text_content_part(text: str) -> dict[str, str]:
        """Build an Anthropic text content block.

        Args:
            text (str): Text to include in the multimodal user message.

        Returns:
            dict[str, str]: Anthropic-compatible text content block.
        """
        return {AnthropicKeys.type: AnthropicKeys.text, AnthropicKeys.text: text}
