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

IMAGE_NAME="${PTY_AGENT_IMAGE:-pty-agent:debian}"
INSTALL_SOURCE="${PTY_AGENT_INSTALL_SOURCE:-crates}"
PLATFORM="${PTY_AGENT_PLATFORM:-}"
PROJECT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
DOCKERFILE="$PROJECT_ROOT/docker/Dockerfile"
NO_CACHE=()

usage() {
  cat <<'EOF'
Usage: shell-pty-agent-docker.sh [OPTIONS] [bash args...]

Launch a clean Debian/Rust Docker shell.

Options:
  --no-install      Build only the Debian/Rust shell image
  --local           Mount this checkout at /src/pty-agent for development
  --rebuild         Build with --no-cache
  -h, --help        Show this help

Environment:
  PTY_AGENT_IMAGE     Docker image tag, default: pty-agent:debian
  PTY_AGENT_PLATFORM  Optional Docker platform override
  PTY_AGENT_VERSION   Optional pty-agent crates.io version
EOF
}

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

if ! command -v docker >/dev/null 2>&1; then
  echo "docker is required but was not found on PATH" >&2
  exit 1
fi

if ! docker info >/dev/null 2>&1; then
  cat >&2 <<'EOF'
docker is installed, but the Docker daemon is not reachable.

Start Docker Desktop, or start your Docker daemon, then rerun this script.
EOF
  exit 1
fi

while [ $# -gt 0 ]; do
  case "$1" in
    --no-install)
      INSTALL_SOURCE="none"
      shift
      ;;
    --local)
      INSTALL_SOURCE="local"
      shift
      ;;
    --rebuild)
      NO_CACHE=(--no-cache)
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      shift
      break
      ;;
    *)
      break
      ;;
  esac
done

BUILD_ARGS=()
RUN_ARGS=()

if [ -n "$PLATFORM" ]; then
  BUILD_ARGS+=(--platform "$PLATFORM")
  RUN_ARGS+=(--platform "$PLATFORM")
fi

docker build \
  "${NO_CACHE[@]}" \
  "${BUILD_ARGS[@]}" \
  --build-arg PTY_AGENT_INSTALL_SOURCE="$INSTALL_SOURCE" \
  --build-arg PTY_AGENT_VERSION="${PTY_AGENT_VERSION:-}" \
  -t "$IMAGE_NAME" \
  -f "$DOCKERFILE" \
  "$PROJECT_ROOT"

VOLUMES=()

if [ "$INSTALL_SOURCE" = "local" ]; then
  VOLUMES+=(-v "$PROJECT_ROOT":/src/pty-agent)
fi

docker run --rm -it \
  "${RUN_ARGS[@]}" \
  -e OPENAI_API_KEY="${OPENAI_API_KEY:-}" \
  -e OPENAI_BASE_URL="${OPENAI_BASE_URL:-}" \
  -e PTY_AGENT_MODEL="${PTY_AGENT_MODEL:-}" \
  -e SHELL=/bin/bash \
  "${VOLUMES[@]}" \
  -w /workspace \
  "$IMAGE_NAME" \
  /bin/bash "$@"
