"""Generic YAML list store with atomic save."""

from pathlib import Path

import yaml


class YamlStore:
    """Read/write a YAML file containing a single list under a top-level key."""

    def __init__(self, path: Path, collection_key: str):
        self.path = path
        self.key = collection_key

    def load(self) -> list[dict]:
        """Load items from YAML. Returns [] if file missing or empty."""
        if not self.path.exists():
            return []
        data = yaml.safe_load(self.path.read_text(encoding="utf-8")) or {}
        return data.get(self.key, [])

    def save(self, items: list[dict]) -> None:
        """Atomic write: tmp file then rename."""
        self.path.parent.mkdir(parents=True, exist_ok=True)
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(
            yaml.dump({self.key: items}, default_flow_style=False, sort_keys=False, allow_unicode=True),
            encoding="utf-8",
        )
        tmp.rename(self.path)
