"""Deterministic runtime helpers for reproducible conversions and pipelines."""

from __future__ import annotations

import os
import random
from typing import Optional

import numpy as np


def set_global_seed(seed: int, *, deterministic_torch: bool = True) -> None:
    """Set global RNG state across Python, NumPy, and torch (if installed)."""
    random.seed(seed)
    np.random.seed(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)

    try:
        import torch
    except ImportError:
        return

    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)

    if deterministic_torch:
        try:
            torch.use_deterministic_algorithms(True, warn_only=True)
        except Exception:
            pass
        if hasattr(torch.backends, "cudnn"):
            torch.backends.cudnn.deterministic = True
            torch.backends.cudnn.benchmark = False


def make_numpy_rng(seed: int) -> np.random.Generator:
    """Create a deterministic local NumPy generator."""
    return np.random.default_rng(seed)


def make_torch_generator(seed: int) -> Optional["object"]:
    """Create a CPU torch.Generator if torch is available."""
    try:
        import torch
    except ImportError:
        return None

    gen = torch.Generator(device="cpu")
    gen.manual_seed(seed)
    return gen

