FROM ghcr.io/anomalyco/opencode:latest

# ── glibc compat + runtimes ──
RUN apk add --no-cache gcompat nodejs curl npm git

# ── Bun (opencode-mem plugin) ──
ARG BUN_VERSION=1.3.9
RUN wget -qO /tmp/bun.zip "https://github.com/oven-sh/bun/releases/download/bun-v${BUN_VERSION}/bun-linux-x64.zip" && \
    unzip -o /tmp/bun.zip -d /tmp/ && \
    cp /tmp/bun-linux-x64/bun /usr/local/bin/bun && \
    chmod +x /usr/local/bin/bun && \
    rm -rf /tmp/bun* && \
    bun --version

# ── CodeGraph ──
RUN npm install -g @colbymchenry/codegraph @colbymchenry/codegraph-linux-x64 && \
    NODE_PATH=$(npm root -g) node -e "require('@colbymchenry/codegraph')"

# ── Python 3.13 + build deps ──
RUN apk add --no-cache python3 py3-pip python3-dev musl-dev gcc postgresql-dev

# ── uv (Python package manager) ──
RUN curl -LsSf https://astral.sh/uv/install.sh | sh && \
    . "$HOME/.local/bin/env" && \
    uv --version

# ── pnpm ──
RUN npm install -g pnpm

# ── PostgreSQL 16 + pgvector ──
RUN apk add --no-cache postgresql postgresql-pgvector

# ── Init PostgreSQL with dev user/db/ext, then remove data dir to save ~40MB ──
RUN mkdir -p /run/postgresql && chown postgres:postgres /run/postgresql && \
    su - postgres -c "initdb -D /var/lib/postgresql/data" && \
    su - postgres -c "pg_ctl -D /var/lib/postgresql/data start" && \
    su - postgres -c "psql -c \"CREATE USER remynd WITH PASSWORD 'remynd';\"" && \
    su - postgres -c "psql -c \"CREATE DATABASE remynd_dev OWNER remynd;\"" && \
    su - postgres -c "psql -d remynd_dev -c 'CREATE EXTENSION IF NOT EXISTS vector;'" && \
    su - postgres -c "pg_ctl -D /var/lib/postgresql/data stop" && \
    rm -rf /var/lib/postgresql/data

# ── Ensure uv on PATH for all shells ──
RUN echo '. "$HOME/.local/bin/env"' > /root/.profile
ENV PATH="/root/.local/bin:$PATH"

# ── Entrypoint: auto-start PostgreSQL, then hand off to CMD ──
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["opencode"]
