import json
import os

from pathlib import Path
from joblib import dump, load
from typing import Any

def create_dir(path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)

def save_json(path: Path, content: dict[str, Any]):
    create_dir(path.parent)

    tmp_path = path.with_suffix(".tmp")

    with tmp_path.open("w", encoding="utf-8") as f:
        json.dump(
            content,
            f,
            ensure_ascii=False,
            indent=2
        )

    os.replace(tmp_path, path)

def load_json(path: Path) -> dict[str, Any]|None:
    if path.exists():
        with path.open("r", encoding="utf-8") as f:
            return json.load(f)

    return None

def save_object(path: Path, obj: object):
    path.parent.mkdir(parents=True, exist_ok=True)
    dump(obj, path)

def load_object(path: Path) -> object | None:
    if path.exists():
        return load(path)
    return None