# AI SDLC Guard — REST API Server
# Multi-stage build for a lean production image

# ---------------------------------------------------------------------------
# Stage 1: Build
# ---------------------------------------------------------------------------
FROM python:3.12-slim AS builder

WORKDIR /build

# Install build dependencies
RUN pip install --no-cache-dir build setuptools>=68.0 setuptools-scm>=8.0

# Copy source
COPY pyproject.toml README.md ./
COPY src/ src/

# Build wheel
RUN python -m build --wheel --outdir /build/dist

# ---------------------------------------------------------------------------
# Stage 2: Runtime
# ---------------------------------------------------------------------------
FROM python:3.12-slim

LABEL maintainer="Max Gerhardson"
LABEL description="AI SDLC Guard REST API server"
LABEL org.opencontainers.image.source="https://github.com/maxgerhardson/ai-sdlc-guard"
LABEL org.opencontainers.image.licenses="LicenseRef-Proprietary"

# Create non-root user
RUN groupadd --gid 1000 guard && \
    useradd --uid 1000 --gid guard --create-home guard

WORKDIR /app

# Install the wheel with server extras
COPY --from=builder /build/dist/*.whl /tmp/
RUN pip install --no-cache-dir "$(ls /tmp/*.whl)[server,azure,sync]" && \
    rm -f /tmp/*.whl && \
    # Compile to .pyc and strip .py source files (IP protection)
    python -m compileall -b /usr/local/lib/python3.12/site-packages/guard/ && \
    find /usr/local/lib/python3.12/site-packages/guard/ -name "*.py" -delete

# Default config directory (mount point)
RUN mkdir -p /app/config /app/out && \
    chown -R guard:guard /app

# Switch to non-root user
USER guard

# Environment defaults
ENV GUARD_OUTPUT_DIR=/app/out
# Expose the API port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1

# Start the server
ENTRYPOINT ["guard"]
CMD ["serve", "--host", "0.0.0.0", "--port", "8000"]
