# ---------------------------------------------------------------------------
# Stage 1: Builder — compile TrueMend into a standalone Nuitka binary
# ---------------------------------------------------------------------------
FROM python:3.10-slim AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    DEBIAN_FRONTEND=noninteractive

WORKDIR /build

# Install build toolchain (C compiler, patchelf for Nuitka)
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        gcc g++ patchelf ccache && \
    rm -rf /var/lib/apt/lists/*

# Install Python dependencies + Nuitka
COPY pyproject.toml ./
RUN pip install --no-cache-dir . 2>/dev/null || \
    pip install --no-cache-dir ast-grep-py colorama fastmcp && \
    pip install --no-cache-dir nuitka ordered-set

# Copy full source tree
COPY cli.py truemend_mcp.py ./
COPY src/ ./src/
COPY specs/ ./specs/
COPY skills/ ./skills/
COPY prompts/ ./prompts/
COPY build/ ./build/

# Compile with Nuitka (skip key embed — no keys in container builds)
RUN python build/nuitka_build.py --platform linux --skip-key-embed


# ---------------------------------------------------------------------------
# Stage 2: Runtime — minimal image with only the binary + data files
# ---------------------------------------------------------------------------
FROM debian:bookworm-slim AS runtime

LABEL maintainer="TrueMend <support@truemend.dev>"
LABEL description="TrueMend — Autonomous Code Improvement Engine (standalone binary)"

RUN apt-get update && \
    apt-get install -y --no-install-recommends git && \
    rm -rf /var/lib/apt/lists/* && \
    useradd --create-home --shell /bin/bash truemend

WORKDIR /app

# Copy the compiled binary from the builder stage
COPY --from=builder /build/dist/truemend /app/truemend

# Copy data files that the binary expects next to itself
COPY --from=builder /build/specs/ /app/specs/
COPY --from=builder /build/skills/ /app/skills/
COPY --from=builder /build/prompts/ /app/prompts/

RUN chmod +x /app/truemend && \
    mkdir -p /workspace && \
    chown -R truemend:truemend /app /workspace

USER truemend

# Create workspace mount point for user code
VOLUME ["/workspace"]

ENTRYPOINT ["/app/truemend"]
CMD ["--help"]
