# ProClaw Interceptor Bridge — Production Dockerfile
#
# Multi-stage build for the Python bridge server.
# Serves both HTTP (FastAPI/uvicorn) and gRPC endpoints.
#
# Build:
#   docker build -t proclaw/interceptor-bridge interceptor/
#
# Run:
#   docker run -p 8100:8100 -p 50051:50051 proclaw/interceptor-bridge

# ---------------------------------------------------------------------------
# Stage 1: Build dependencies
# ---------------------------------------------------------------------------
FROM python:3.11-slim AS builder

WORKDIR /build

# Install build dependencies
RUN pip install --no-cache-dir --upgrade pip setuptools wheel

# Copy dependency files first (layer caching)
COPY ../pyproject.toml /build/pyproject.toml

# Install only the interceptor extras
RUN pip install --no-cache-dir --prefix=/install \
    pydantic>=2.0.0 \
    fastapi>=0.104.0 \
    uvicorn[standard]>=0.24.0 \
    grpcio>=1.60.0 \
    structlog>=23.2.0

# ---------------------------------------------------------------------------
# Stage 2: Production image
# ---------------------------------------------------------------------------
FROM python:3.11-slim AS runtime

# Security: non-root user
RUN groupadd -r proclaw && useradd -r -g proclaw proclaw

WORKDIR /app

# Copy installed Python packages from builder
COPY --from=builder /install /usr/local

# Copy contracts (read-only dependency)
COPY contracts/ /app/contracts/

# Copy interceptor bridge code
COPY interceptor/bridge/ /app/interceptor/bridge/
COPY interceptor/__init__.py /app/interceptor/__init__.py

# Copy lib dependencies (read-only)
COPY lib/zero_trust/ /app/lib/zero_trust/
COPY lib/streaming/ /app/lib/streaming/

# Ensure package structure
RUN touch /app/lib/__init__.py /app/lib/zero_trust/__init__.py

# Set Python path
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

# Default configuration (override via env vars or docker-compose)
ENV PROCLAW_BRIDGE_HTTP_HOST=0.0.0.0
ENV PROCLAW_BRIDGE_HTTP_PORT=8100
ENV PROCLAW_BRIDGE_GRPC_PORT=50051
ENV PROCLAW_FAIL_CLOSED=true
ENV PROCLAW_LOG_LEVEL=INFO

# Expose both HTTP and gRPC ports
EXPOSE 8100 50051

# Health check: hit the HTTP health endpoint
HEALTHCHECK --interval=15s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8100/health')" || exit 1

# Switch to non-root user
USER proclaw

# Start both HTTP and gRPC servers via the dual entrypoint
CMD ["python", "-m", "interceptor.bridge"]
