"""File I/O utilities for MoltenFlow.

This module provides functions for reading and writing files, managing
directories, and handling JSON serialization.
"""

from __future__ import annotations
from pathlib import Path
from typing import Any
import json
import os


def ensure_dir(path: str | Path) -> Path:
    """Create directory and parents if they don't exist.

    Args:
        path: Path to directory

    Returns:
        Path object to the directory
    """
    p = Path(path)
    p.mkdir(parents=True, exist_ok=True)
    return p


def save_json(path: str, obj: Any) -> None:
    """Save object as JSON file.

    Args:
        path: Output file path
        obj: Object to serialize
    """
    os.makedirs(os.path.dirname(path), exist_ok=True)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, indent=2)


def load_json(path: str) -> Any:
    """Load JSON file.

    Args:
        path: Path to JSON file

    Returns:
        Deserialized object
    """
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)
