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

IMAGE_NAME="${PTY_AGENT_IMAGE:-pty-agent:debian}"
CONTAINER_NAME="${PTY_AGENT_CONTAINER:-pty-agent-shell}"
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_CONTAINER Docker container name, default: pty-agent-shell
  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=()
ENV_ARGS=(-e SHELL=/bin/bash)

if [ -n "${OPENAI_API_KEY:-}" ]; then
  ENV_ARGS+=(-e OPENAI_API_KEY="$OPENAI_API_KEY")
fi

if [ -n "${OPENAI_BASE_URL:-}" ]; then
  ENV_ARGS+=(-e OPENAI_BASE_URL="$OPENAI_BASE_URL")
fi

if [ -n "${PTY_AGENT_MODEL:-}" ]; then
  ENV_ARGS+=(-e PTY_AGENT_MODEL="$PTY_AGENT_MODEL")
fi

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

docker run -it \
  --name "$CONTAINER_NAME" \
  "${RUN_ARGS[@]}" \
  "${ENV_ARGS[@]}" \
  "${VOLUMES[@]}" \
  -w /workspace \
  "$IMAGE_NAME" \
  /bin/bash "$@"
