"""Shared utility helpers for the Icarus core engine."""

from __future__ import annotations

import contextlib
import logging
import os
import tempfile
import tomllib
from pathlib import Path

import tomli_w

logger = logging.getLogger(__name__)


def load_toml(config_path: Path) -> dict:
    """Read a TOML file, returning an empty dict on any failure."""
    if not config_path.exists():
        return {}
    try:
        with config_path.open("rb") as f:
            return tomllib.load(f)
    except (tomllib.TOMLDecodeError, PermissionError, OSError) as e:
        logger.warning("Could not read %s: %s", config_path, e)
        return {}


def save_toml(config_path: Path, data: dict) -> None:
    """Atomic write: temp file in same dir, then rename.

    Creates parent directories if needed.  Cleans up the temp file
    on any failure.
    """
    config_path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp_path = tempfile.mkstemp(dir=config_path.parent, suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as f:
            tomli_w.dump(data, f)
        Path(tmp_path).replace(config_path)
    except BaseException:
        with contextlib.suppress(OSError):
            Path(tmp_path).unlink()
        raise
