"""Instagram CRDT document builder.

Builds pycrdt Doc objects from ParsedInstagramDocument models.
"""

from __future__ import annotations

from typing import Any

from pycrdt import Doc, XmlElement

from marqetive.utils.crdt.builders.base import BaseCRDTBuilder
from marqetive.utils.crdt.models import ParsedInstagramDocument


class InstagramCRDTBuilder(BaseCRDTBuilder[ParsedInstagramDocument]):
    """Builder for Instagram CRDT documents."""

    @property
    def platform_name(self) -> str:
        return "instagram"

    @property
    def root_node_type(self) -> str:
        return "instagrampost"

    def build_document(
        self, parsed: ParsedInstagramDocument, fragment_name: str = "default"
    ) -> Doc[Any]:
        """Build an Instagram CRDT Doc from a parsed document."""
        post = parsed.post
        attrs: dict[str, str] = {}
        if post.id is not None:
            attrs["id"] = post.id
        if post.media:
            attrs["media"] = self._build_media_attribute(post.media)
        attrs["content_type"] = post.content_type.value
        if post.location is not None:
            attrs["location"] = post.location
        if post.music is not None:
            attrs["music"] = post.music
        attrs["share_to_feed"] = str(post.share_to_feed).lower()
        if post.location_name is not None:
            attrs["location_name"] = post.location_name
        if post.cover_url is not None:
            attrs["cover_url"] = post.cover_url

        paragraphs = self._build_text_paragraphs(post.caption)
        children: list[XmlElement] = [
            XmlElement("instagrampost", attributes=attrs, contents=paragraphs)
        ]

        # Build comment node if present
        if parsed.comment is not None:
            comment_attrs: dict[str, str] = {}
            if parsed.comment.id is not None:
                comment_attrs["id"] = parsed.comment.id
            comment_paragraphs = self._build_text_paragraphs(parsed.comment.text)
            children.append(
                XmlElement(
                    "instagramcomment",
                    attributes=comment_attrs,
                    contents=comment_paragraphs,
                )
            )

        return self._create_doc_with_fragment(fragment_name, children)
