# syntax=docker/dockerfile:1

# ── Stage 1: Clone monorepo (build arg is discarded with this stage) ──
FROM python:3.12-slim AS cloner

RUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/*

ARG GITHUB_TOKEN=""
RUN mkdir -p /workspace && \
    if [ -n "$GITHUB_TOKEN" ]; then \
        git clone --depth 1 "https://x-access-token:${GITHUB_TOKEN}@github.com/snokam/monorepo.git" /workspace && \
        cd /workspace && git remote set-url origin https://github.com/snokam/monorepo.git; \
    else \
        git -C /workspace init; \
    fi

# ── Stage 2: Final image ──
FROM python:3.12-slim

# Git (for worktrees), Node.js (for Claude Code CLI), SSH (for git operations)
RUN apt-get update && apt-get install -y --no-install-recommends \
        git curl openssh-client ca-certificates && \
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
    apt-get install -y --no-install-recommends nodejs && \
    npm install -g @anthropic-ai/claude-code && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY . .
RUN pip install --no-cache-dir .

# Create non-root user (Claude Code refuses --dangerously-skip-permissions as root)
RUN useradd -m -s /bin/bash coder

# Copy pre-cloned workspace from stage 1 (no token in this layer)
COPY --from=cloner /workspace /workspace
RUN chown -R coder:coder /workspace

RUN mkdir -p /worktrees && chown coder:coder /worktrees

USER coder

# Git credential helper scoped to github.com only — uses GITHUB_TOKEN env var at runtime
RUN printf '#!/bin/sh\necho "username=x-access-token\npassword=$GITHUB_TOKEN"\n' > /home/coder/git-credential-env.sh && \
    chmod +x /home/coder/git-credential-env.sh && \
    git config --global credential.https://github.com.helper /home/coder/git-credential-env.sh && \
    git config --global user.name "Olaf the Vibecoder" && \
    git config --global user.email "olaf@snokam.no"

ENV PORT=8765
ENV VOICE_WORKTREES_DIR=/worktrees
EXPOSE 8765

CMD ["vibecoder-serve", "--host", "0.0.0.0", "--port", "8765", "--repo", "/workspace"]
