# ==========================================================================
# Kore Platform -- Multi-stage Docker build
# ==========================================================================
# Stage 1: builder  -- install dependencies in an isolated layer
# Stage 2: runtime  -- minimal image with non-root user
# ==========================================================================

# ── Builder ──────────────────────────────────────────────────────────
FROM python:3.11-slim AS builder

WORKDIR /build

# System deps needed for building wheels
RUN apt-get update && \
    apt-get install -y --no-install-recommends gcc libpq-dev && \
    rm -rf /var/lib/apt/lists/*

# Copy only dependency metadata first (better layer caching)
COPY pyproject.toml README.md LICENSE ./
COPY src/ src/

# Install into a prefix that we can copy to runtime
RUN pip install --no-cache-dir --prefix=/install ".[all]"

# ── Runtime ──────────────────────────────────────────────────────────
FROM python:3.11-slim AS runtime

LABEL maintainer="IAFiscal <dev@iafiscal.com>"
LABEL org.opencontainers.image.source="https://github.com/iafiscal1212/kore-platform"
LABEL org.opencontainers.image.description="Kore Platform -- Enterprise AI Orchestration"
LABEL org.opencontainers.image.licenses="MIT"

# Runtime system deps
RUN apt-get update && \
    apt-get install -y --no-install-recommends libpq5 curl tini && \
    rm -rf /var/lib/apt/lists/*

# Non-root user
RUN groupadd --gid 1000 kore && \
    useradd --uid 1000 --gid kore --shell /bin/bash --create-home kore

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

# Copy application source
WORKDIR /app
COPY --chown=kore:kore src/ src/
COPY --chown=kore:kore flows/ flows/
COPY --chown=kore:kore scripts/ scripts/

# Environment
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    KORE_LOG_LEVEL=INFO \
    KORE_SANDBOX_POLICY=strict

# Switch to non-root
USER kore

# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8000/healthz || exit 1

EXPOSE 8000

# Use tini as init to properly handle signals
ENTRYPOINT ["tini", "--"]
CMD ["python", "-m", "kore_platform"]
