from __future__ import annotations

from pathlib import Path

from one_run.constants import DEFAULT_RUNS_DIR
from one_run.errors import BackendError, OneRunError
from one_run.run_dir import RunPaths, allocate_run_paths, resolve_run_paths


def alloc_run_dir(project_root: Path, experiment_name: str) -> tuple[str, RunPaths]:
    runs_root = project_root / DEFAULT_RUNS_DIR
    runs_root.mkdir(parents=True, exist_ok=True)
    try:
        return allocate_run_paths(runs_root, experiment_name)
    except FileExistsError as exc:
        raise BackendError(str(exc)) from exc


def load_run_paths(project_root: Path, run_id: str) -> RunPaths:
    run_dir = project_root / DEFAULT_RUNS_DIR / run_id
    if not run_dir.exists():
        raise OneRunError(f"run not found: {run_id}")
    return resolve_run_paths(run_dir)
