#!/usr/bin/env bash
set -euo pipefail

# Resolve workspace root (this repo) regardless of where the script is called from.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"

# Some managed macOS environments set TMPDIR to slow/unusual locations.
# Force a local temp directory for predictable behavior.
export TMPDIR="/tmp"

VENV_PY="${WORKSPACE_ROOT}/.venv/bin/python"
NANOGPT_DIR="${WORKSPACE_ROOT}/oss_llm/nanoGPT"

require_python3() {
  if ! command -v python3 >/dev/null 2>&1; then
    echo "ERROR: python3 not found in PATH" >&2
    exit 1
  fi
}

require_curl() {
  if ! command -v curl >/dev/null 2>&1; then
    echo "ERROR: curl not found in PATH" >&2
    exit 1
  fi
}

ensure_venv() {
  if [[ -x "${VENV_PY}" ]]; then
    return 0
  fi

  require_python3
  echo "Creating workspace venv at: ${WORKSPACE_ROOT}/.venv" >&2
  python3 -m venv "${WORKSPACE_ROOT}/.venv"
}

require_venv() {
  ensure_venv
  if [[ ! -x "${VENV_PY}" ]]; then
    echo "ERROR: Failed to create venv python at: ${VENV_PY}" >&2
    exit 1
  fi
}

require_git() {
  if ! command -v git >/dev/null 2>&1; then
    echo "ERROR: git not found in PATH" >&2
    exit 1
  fi
}

cd_nanogpt() {
  if [[ ! -d "${NANOGPT_DIR}" ]]; then
    echo "ERROR: nanoGPT repo not found at ${NANOGPT_DIR}" >&2
    echo "Run: bash oss_llm/testNanoGPT/10_clone_nanogpt.sh" >&2
    exit 1
  fi
  cd "${NANOGPT_DIR}"
}
