"""YamlAdapter - YAML parsing with ruamel.yaml.

Contract: CNT-T3-ADP-002
Implements: YamlPort
"""

from pathlib import Path
from typing import Any

from ruamel.yaml import YAML

from laida_cli.ports.yaml_port import YamlPort


class YamlAdapter:
    """Adapter for YAML operations using ruamel.yaml.

    Uses ruamel.yaml for round-trip preservation of comments and formatting.
    """

    def __init__(self) -> None:
        """Initialize YAML parser."""
        self._yaml = YAML()
        self._yaml.preserve_quotes = True
        self._yaml.default_flow_style = False

    def parse(self, content: str) -> dict[str, Any]:
        """Parse YAML string to dictionary.

        Args:
            content: YAML string

        Returns:
            Parsed dictionary

        Raises:
            ValueError: If parsing fails
        """
        from io import StringIO

        try:
            result = self._yaml.load(StringIO(content))
            return dict(result) if result else {}
        except Exception as e:
            raise ValueError(f"Failed to parse YAML: {e}") from e

    def dump(self, data: dict[str, Any]) -> str:
        """Dump dictionary to YAML string.

        Args:
            data: Dictionary to dump

        Returns:
            YAML string
        """
        from io import StringIO

        stream = StringIO()
        self._yaml.dump(data, stream)
        return stream.getvalue()

    def parse_file(self, path: Path) -> dict[str, Any]:
        """Parse YAML file to dictionary.

        Args:
            path: Path to YAML file

        Returns:
            Parsed dictionary

        Raises:
            FileNotFoundError: If file does not exist
            ValueError: If parsing fails
        """
        content = path.read_text(encoding="utf-8")
        return self.parse(content)

    def dump_file(self, path: Path, data: dict[str, Any]) -> None:
        """Dump dictionary to YAML file.

        Args:
            path: Path to output file
            data: Dictionary to dump
        """
        with open(path, "w", encoding="utf-8") as f:
            self._yaml.dump(data, f)


# Compile-time check that adapter implements the protocol
_: YamlPort = YamlAdapter()
