"""Theme loader for TCSS files."""

from pathlib import Path
from typing import Any

from cleave.core.yaml_utils import parse_yaml_simple


class ThemeLoader:
    """Loads themes from TCSS files and metadata from YAML."""

    def load_theme_file(self, theme_path: Path) -> str | None:
        """Load theme content from a TCSS file.

        Args:
            theme_path: Path to the .tcss file.

        Returns:
            Theme content as string, or None if file doesn't exist.
        """
        if not theme_path.exists():
            return None

        try:
            return theme_path.read_text(encoding="utf-8")
        except Exception:
            return None

    def load_metadata(self, metadata_path: Path) -> dict[str, Any] | None:
        """Load theme metadata from YAML file.

        Args:
            metadata_path: Path to the metadata YAML file.

        Returns:
            Metadata dictionary, or None if file doesn't exist or is invalid.
        """
        if not metadata_path.exists():
            return None

        try:
            content = metadata_path.read_text(encoding="utf-8")
            data = parse_yaml_simple(content)
            if isinstance(data, dict):
                return data
            return None
        except Exception:
            return None

    def load_theme_with_metadata(self, theme_dir: Path, theme_name: str) -> dict[str, Any] | None:
        """Load a theme with its metadata.

        Args:
            theme_dir: Directory containing theme files.
            theme_name: Name of the theme (without extension).

        Returns:
            Dictionary with 'name', 'content', and optional metadata fields.
        """
        theme_file = theme_dir / f"{theme_name}.tcss"
        content = self.load_theme_file(theme_file)

        if content is None:
            return None

        result: dict[str, Any] = {
            "name": theme_name,
            "content": content,
        }

        # Try to load metadata
        metadata_file = theme_dir / f"{theme_name}-metadata.yaml"
        metadata = self.load_metadata(metadata_file)

        if metadata:
            result.update(metadata)

        return result
