from pathlib import Path
from typing import Any

import yaml

import logging

logger = logging.getLogger(__name__)


def ensure_dir(path: Path) -> None:
    """Ensures a directory exists. Raises on fatal errors."""
    try:
        path.mkdir(parents=True, exist_ok=True)
    except Exception as e:
        logger.error(f"Could not create directory {path}: {e}")


def read_file(path: str | Path) -> str | None:
    """Safe file reader with logging, returns None if missing."""
    path = Path(path)

    try:
        return path.read_text(encoding="utf-8").strip()
    except FileNotFoundError:
        logger.debug(f"File not found: {path}")
        return None
    except Exception as e:
        logger.warning(f"Error reading {path}: {e}")
        return None


def load_yaml_file(path: str | Path) -> dict[str, Any]:  # pyright: ignore[reportExplicitAny]
    """Load a YAML file safely. Returns {} on empty files but throws on errors."""

    path = Path(path)

    logger.debug(f"Loading YAML file: {path}")

    if not path.exists():
        logger.error(f"{path!s} file does not exist")
        return {}

    if not path.is_file():
        logger.error(f"{path!s} is not a regular file")
        return {}

    try:
        with path.open("r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
            if not data:
                logger.error(f"{path!s} File is empty!")
                return {}
            return data
    except yaml.YAMLError as e:
        logger.error(f"{path!s} YAML parsing error: {e}")
        return {}
    except Exception as e:
        logger.error(f"{path!s} unexpected error: {e}")
        return {}
