"""LinkedIn CRDT document builder.

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


class LinkedInCRDTBuilder(BaseCRDTBuilder[ParsedLinkedInDocument]):
    """Builder for LinkedIn CRDT documents."""

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

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

    def build_document(
        self, parsed: ParsedLinkedInDocument, fragment_name: str = "default"
    ) -> Doc[Any]:
        """Build a LinkedIn CRDT Doc from a parsed document."""
        children: list[XmlElement] = []

        # Build post node
        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.pdf is not None:
            attrs["pdf"] = post.pdf
        attrs["postVisibility"] = post.visibility.value
        if post.og is not None:
            attrs["og"] = post.og
        if post.pdf_images is not None:
            attrs["pdf_images"] = post.pdf_images

        paragraphs = self._build_text_paragraphs(post.text)
        children.append(
            XmlElement("linkedinpost", 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
            if parsed.comment.media:
                comment_attrs["media"] = self._build_media_attribute(
                    parsed.comment.media
                )
            comment_attrs["hidden"] = str(parsed.comment.hidden).lower()
            comment_paragraphs = self._build_text_paragraphs(parsed.comment.text)
            children.append(
                XmlElement(
                    "linkedincomment",
                    attributes=comment_attrs,
                    contents=comment_paragraphs,
                )
            )

        return self._create_doc_with_fragment(fragment_name, children)
