# pi-devbox — pi coding-agent container
#
# Builds on top of the opencode-devbox base image, which provides:
#   Debian trixie, Node.js, AWS CLI, mempalace + MCP server, gitea-mcp,
#   dev tools (neovim, tmux, bat, eza, fzf, zoxide, ripgrep, uv, rustup),
#   user setup (developer/gosu), entrypoints, chromadb prewarm.
#
# This image adds only pi itself and its companion repos.
#
# Build args:
#   BASE_IMAGE        — base image to build from (default: base-latest)
#   PI_VERSION        — pi npm version: "latest" or a pinned version e.g. "0.74.0"
#   PI_TOOLKIT_REF    — git ref for pi-toolkit (default: main)
#   PI_EXTENSIONS_REF — git ref for pi-extensions (default: main)

ARG BASE_IMAGE=joakimp/opencode-devbox:base-latest
FROM ${BASE_IMAGE}

# PI_VERSION should be passed explicitly by CI as a concrete version
# (e.g. PI_VERSION=0.75.5, derived from the git tag). The default `latest`
# is for local dev convenience only — it has a known cache-hit footgun
# when used in registry-cached CI builds. See .gitea/workflows/docker-
# publish.yml § "Resolve PI_VERSION from tag" and AGENTS.md gotcha for
# the full story (silent same-bytes-across-releases regression discovered
# 2026-05-23 affecting all builds v0.74.0..v0.75.5).
ARG PI_VERSION=latest
ARG PI_TOOLKIT_REF=main
ARG PI_EXTENSIONS_REF=main

# Install pi and clone companion repos.
# NPM_CONFIG_PREFIX is overridden to /usr so the baked binary lands at the
# system prefix — same pattern as opencode-devbox's variant Dockerfile.
# At runtime, NPM_CONFIG_PREFIX is reset to /home/developer/.pi/npm-global
# (inherited from base ENV) so user-installed packages land on the named
# volume and survive container recreate.
#
# git clone is wrapped in a retry loop because gitea.jordbo.se occasionally
# returns transient HTTP 500s on the first request after idle.
RUN set -e && \
    git_clone_retry() { \
      url="$1"; ref="$2"; dest="$3"; \
      for i in 1 2 3 4 5; do \
        if git clone --depth 1 --branch "$ref" "$url" "$dest"; then return 0; fi; \
        rm -rf "$dest"; \
        echo "git clone $url failed (attempt $i/5), retrying in $((i*5))s..."; \
        sleep $((i*5)); \
      done; \
      return 1; \
    } && \
    if [ "${PI_VERSION}" = "latest" ]; then \
      NPM_CONFIG_PREFIX=/usr npm install -g @earendil-works/pi-coding-agent ; \
    else \
      NPM_CONFIG_PREFIX=/usr npm install -g @earendil-works/pi-coding-agent@${PI_VERSION} ; \
    fi && \
    pi --version && \
    git_clone_retry https://gitea.jordbo.se/joakimp/pi-toolkit.git "${PI_TOOLKIT_REF}" /opt/pi-toolkit && \
    git_clone_retry https://gitea.jordbo.se/joakimp/pi-extensions.git "${PI_EXTENSIONS_REF}" /opt/pi-extensions && \
    echo "pi-toolkit at $(cd /opt/pi-toolkit && git rev-parse --short HEAD)" && \
    echo "pi-extensions at $(cd /opt/pi-extensions && git rev-parse --short HEAD)"

# WORKDIR / ENTRYPOINT / CMD inherited from base.
