"""TikTok CRDT document builder.

Builds pycrdt Doc objects from ParsedTikTokDocument 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 ParsedTikTokDocument


class TikTokCRDTBuilder(BaseCRDTBuilder[ParsedTikTokDocument]):
    """Builder for TikTok CRDT documents."""

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

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

    def build_document(
        self, parsed: ParsedTikTokDocument, fragment_name: str = "default"
    ) -> Doc[Any]:
        """Build a TikTok 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)
        if post.location is not None:
            attrs["location"] = post.location
        if post.music is not None:
            attrs["music"] = post.music

        paragraphs = self._build_text_paragraphs(post.title)
        children = [XmlElement("tiktokpost", attributes=attrs, contents=paragraphs)]

        return self._create_doc_with_fragment(fragment_name, children)
