"""Small, atomic YAML state writer for server-local Runtime projection."""

from __future__ import annotations

import os
import tempfile

import yaml


def write_yaml_atomic(path: str, payload: dict) -> None:
    directory = os.path.dirname(path)
    if not directory:
        raise ValueError("runtime state path must include a parent directory")

    os.makedirs(directory, mode=0o700, exist_ok=True)
    os.chmod(directory, 0o700)
    descriptor, temporary = tempfile.mkstemp(prefix=".streams-", suffix=".tmp", dir=directory)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
            yaml.safe_dump(payload, handle, sort_keys=False, allow_unicode=True)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
    except Exception:
        try:
            os.unlink(temporary)
        except FileNotFoundError:
            pass
        raise
