from __future__ import annotations

from pathlib import Path
import pickle
import json


def save_model(obj, path: str | Path, metadata: dict | None = None) -> Path:
    """Save model object + optional metadata sidecar."""
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    with p.open("wb") as f:
        pickle.dump(obj, f)
    if metadata is not None:
        p.with_suffix(p.suffix + ".meta.json").write_text(
            json.dumps(metadata, indent=2), encoding="utf-8"
        )
    return p


def load_model(path: str | Path):
    """Load model object from pickle path."""
    with Path(path).open("rb") as f:
        return pickle.load(f)
