from __future__ import annotations

import json
import os
import random
from pathlib import Path
import platform
import numpy as np


def set_global_seed(seed: int, torch: bool = False) -> None:
    """Set seeds across random and numpy (optionally torch)."""
    random.seed(seed)
    np.random.seed(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)
    if torch:
        try:
            import torch as _torch

            _torch.manual_seed(seed)
            _torch.cuda.manual_seed_all(seed)
            _torch.backends.cudnn.deterministic = True
            _torch.backends.cudnn.benchmark = False
        except Exception:
            pass


def snapshot_environment(path: str | Path) -> Path:
    """Write lightweight environment metadata JSON."""
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    data = {
        "python": platform.python_version(),
        "platform": platform.platform(),
        "env": {k: v for k, v in os.environ.items() if k in {"PYTHONHASHSEED"}},
    }
    p.write_text(json.dumps(data, indent=2), encoding="utf-8")
    return p
