import os
import random
from typing import Any, Dict

import torch


def set_seed(seed: int = 42, deterministic: bool = True) -> None:
    random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    if deterministic:
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False


def ensure_dir(path: str) -> None:
    os.makedirs(path, exist_ok=True)


def save_checkpoint(state: Dict[str, Any], is_best: bool, output_dir: str) -> None:
    ensure_dir(output_dir)
    last_path = os.path.join(output_dir, "last.pth")
    torch.save(state, last_path)
    if is_best:
        torch.save(state, os.path.join(output_dir, "best.pth"))

