"""LinkedIn-specific CRDT document parser.

This module provides parsing for CRDT documents containing LinkedIn
post data with linkedinpost and linkedincomment nodes.
"""

from __future__ import annotations

from datetime import UTC, datetime
from typing import TYPE_CHECKING

from marqetive.utils.crdt.exceptions import CRDTEmptyDocumentError, CRDTParseError
from marqetive.utils.crdt.models import (
    LinkedInCommentContent,
    LinkedInPostContent,
    ParsedLinkedInDocument,
    PostVisibility,
)
from marqetive.utils.crdt.platforms.base import BaseCRDTParser

if TYPE_CHECKING:
    from pycrdt import Doc, XmlElement

# LinkedIn platform limits
LINKEDIN_MAX_CHARACTERS = 3000
LINKEDIN_COMMENT_MAX_CHARACTERS = 1250


class LinkedInCRDTParser(BaseCRDTParser[ParsedLinkedInDocument]):
    """Parser for LinkedIn CRDT documents.

    Handles parsing of linkedinpost and linkedincomment nodes.
    Supports media attachments, PDF documents, and visibility settings.

    Validation rules:
        - Max 3000 characters for post
        - Max 1250 characters for comment
        - Multiple media allowed
        - PDF attachments supported
        - Visibility settings: PUBLIC, CONNECTIONS, LOGGED_IN
    """

    @property
    def platform_name(self) -> str:
        """Return the platform name."""
        return "linkedin"

    @property
    def root_node_type(self) -> str:
        """Return the root node type for LinkedIn."""
        return "linkedinpost"

    def parse_document(
        self, doc: Doc, fragment_name: str = "default"
    ) -> ParsedLinkedInDocument:
        """Parse a LinkedIn CRDT document.

        Args:
            doc: The pycrdt Doc object to parse
            fragment_name: Name of the XML fragment to parse

        Returns:
            ParsedLinkedInDocument with parsed post and optional comment

        Raises:
            CRDTEmptyDocumentError: If no post found
            CRDTParseError: If parsing fails
        """
        fragment = self._get_fragment(doc, fragment_name)
        raw_attributes = self._get_node_attributes(fragment)

        # Find the linkedinpost node
        post_nodes = self._find_nodes_by_type(fragment, self.root_node_type)

        if not post_nodes:
            raise CRDTEmptyDocumentError(
                "No LinkedIn post found in document",
                fragment_name=fragment_name,
            )

        # Parse the main post
        try:
            post = self._parse_post(post_nodes[0])
        except Exception as e:
            raise CRDTParseError(
                f"Failed to parse LinkedIn post: {e}",
                platform=self.platform_name,
                node_type=self.root_node_type,
            ) from e

        # Find and parse optional comment
        comment: LinkedInCommentContent | None = None
        comment_nodes = self._find_nodes_by_type(fragment, "linkedincomment")
        if comment_nodes:
            try:
                comment = self._parse_comment(comment_nodes[0])
            except Exception as e:
                raise CRDTParseError(
                    f"Failed to parse LinkedIn comment: {e}",
                    platform=self.platform_name,
                    node_type="linkedincomment",
                ) from e

        return ParsedLinkedInDocument(
            post=post,
            comment=comment,
            raw_attributes=raw_attributes,
            parsed_at=datetime.now(UTC),
        )

    def validate_schema(self, doc: Doc, fragment_name: str = "default") -> list[str]:
        """Validate a LinkedIn CRDT document.

        Args:
            doc: The pycrdt Doc object to validate
            fragment_name: Name of the XML fragment to validate

        Returns:
            List of validation errors (empty if valid)
        """
        errors: list[str] = []

        try:
            result = self.parse_document(doc, fragment_name)
        except CRDTEmptyDocumentError as e:
            return [str(e)]
        except CRDTParseError as e:
            return [str(e)]

        # Validate post text length
        text_error = self._validate_text_length(
            result.post.text, LINKEDIN_MAX_CHARACTERS, "Post text"
        )
        if text_error:
            errors.append(text_error)

        # Validate comment if present
        if result.comment:
            comment_error = self._validate_text_length(
                result.comment.text, LINKEDIN_COMMENT_MAX_CHARACTERS, "Comment text"
            )
            if comment_error:
                errors.append(comment_error)

        return errors

    def _parse_post(self, node: XmlElement) -> LinkedInPostContent:
        """Parse a linkedinpost node.

        Matches production linkedin_parser.py:73-88 behavior.

        Args:
            node: The linkedinpost XML node

        Returns:
            LinkedInPostContent with parsed data
        """
        attrs = self._get_node_attributes(node)

        # Read post ID from attrs
        post_id = attrs.get("id")
        if post_id is not None:
            post_id = str(post_id)

        # Extract text content
        text = self._extract_text(node)

        # Parse media via space-separated URL strings
        media = self._parse_media_urls(node, "media")

        # Read PDF as simple string
        pdf = attrs.get("pdf")
        if pdf is not None:
            pdf = str(pdf)

        # Parse visibility from "postVisibility" attr (production uses this name)
        visibility_str = attrs.get("postVisibility", "PUBLIC")
        visibility = self._parse_visibility(str(visibility_str))

        return LinkedInPostContent(
            id=post_id,
            text=text,
            media=media,
            pdf=pdf,
            visibility=visibility,
        )

    def _parse_comment(self, node: XmlElement) -> LinkedInCommentContent:
        """Parse a linkedincomment node.

        Matches production linkedin_parser.py:90-95 — text only, no media.

        Args:
            node: The linkedincomment XML node

        Returns:
            LinkedInCommentContent with parsed data
        """
        attrs = self._get_node_attributes(node)
        comment_id = attrs.get("id")
        if comment_id is not None:
            comment_id = str(comment_id)
        text = self._extract_text(node)
        return LinkedInCommentContent(id=comment_id, text=text)

    def _parse_visibility(self, visibility_str: str) -> PostVisibility:
        """Parse visibility string to enum.

        Handles uppercase values matching schema/production defaults.

        Args:
            visibility_str: Visibility setting string

        Returns:
            PostVisibility enum value
        """
        visibility_map = {
            "PUBLIC": PostVisibility.PUBLIC,
            "CONNECTIONS": PostVisibility.CONNECTIONS,
            "LOGGED_IN": PostVisibility.LOGGED_IN,
        }

        return visibility_map.get(visibility_str.strip(), PostVisibility.PUBLIC)
