"""Sheet class for XMind 16."""

from __future__ import annotations

from typing import Optional

from .topic import Topic
from .utils import generate_id


class Sheet:
    """Represents a sheet (canvas) in an XMind workbook.
    
    A sheet contains a root topic and represents a single mind map.
    """
    
    def __init__(self, title: str = "Sheet", id: Optional[str] = None):
        """Initialize a Sheet.
        
        Args:
            title: The sheet title.
            id: Optional unique identifier. If not provided, one will be generated.
        """
        self._id = id or generate_id()
        self._title = title
        self._root_topic: Optional[Topic] = None
    
    @property
    def id(self) -> str:
        """Get the sheet's unique identifier."""
        return self._id
    
    @property
    def title(self) -> str:
        """Get the sheet's title."""
        return self._title
    
    @title.setter
    def title(self, value: str) -> None:
        """Set the sheet's title."""
        self._title = value
    
    @property
    def root_topic(self) -> Optional[Topic]:
        """Get the root topic of the sheet."""
        return self._root_topic
    
    def get_root_topic(self) -> Topic:
        """Get or create the root topic of the sheet.
        
        Returns:
            The root topic, creating one if it doesn't exist.
        """
        if self._root_topic is None:
            self._root_topic = Topic(title="Central Topic")
        return self._root_topic
    
    def set_root_topic(self, topic: Topic) -> None:
        """Set the root topic of the sheet.
        
        Args:
            topic: The topic to set as root.
        """
        self._root_topic = topic
    
    def to_dict(self) -> dict:
        """Convert the sheet to a dictionary representation (XMind 16 format).
        
        Returns:
            A dictionary representing the sheet.
        """
        data = {
            "id": self._id,
            "class": "sheet",
            "title": self._title,
        }
        
        if self._root_topic:
            data["rootTopic"] = self._root_topic.to_dict()
        
        return data
    
    @classmethod
    def from_dict(cls, data: dict) -> Sheet:
        """Create a Sheet from a dictionary.
        
        Args:
            data: The dictionary containing sheet data.
            
        Returns:
            A new Sheet instance.
        """
        sheet = cls(
            title=data.get("title", "Sheet"),
            id=data.get("id")
        )
        
        if "rootTopic" in data:
            sheet._root_topic = Topic.from_dict(data["rootTopic"])
        
        return sheet
    
    def __repr__(self) -> str:
        """Return a string representation of the sheet."""
        return f"Sheet(id={self._id[:8]}..., title='{self._title}')"
