# 1. Builder Stage
FROM python:3.14-slim AS builder

# Optimized build: Use uv with cache mounting
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Install build dependencies
# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Enable uv cache mounting to speed up repeated builds
ENV UV_CACHE_DIR=/root/.cache/uv

# Copy manifest files
COPY pyproject.toml uv.lock ./
COPY shims/ ./shims/
# .dockerignore handles excluding .git if it exists, but we copy it if needed for hatch-vcs
# Use a wildcard to make the copy optional if .git doesn't exist in some contexts
COPY .gi[t] ./.git/

# Copy local manifest dependency to /coreason-manifest/ to satisfy relative path dependency
COPY coreason-manifest* /coreason-manifest/

# Copy local URN authority dependency to /coreason-urn-authority/ to satisfy relative path dependency
COPY coreason-urn-authority* /coreason-urn-authority/

# Install dependencies into a local .venv
# Use --extra to conditionally install heavy ML dependencies (inference group)
ARG EXTRAS=""
RUN --mount=type=cache,target=/root/.cache/uv \
    if [ -z "$EXTRAS" ]; then \
        uv sync --frozen --no-install-project --no-dev; \
    else \
        uv sync --frozen --no-install-project --no-dev --extra "$EXTRAS"; \
    fi

# Copy source and install the project
COPY src ./src
COPY README.md LICENSE ./
RUN --mount=type=cache,target=/root/.cache/uv \
    if [ -z "$EXTRAS" ]; then \
        uv sync --frozen --no-dev; \
    else \
        uv sync --frozen --no-dev --extra "$EXTRAS"; \
    fi


# 2. Execution Stage
FROM python:3.14-slim

LABEL org.opencontainers.image.source="https://github.com/CoReason-AI/coreason-runtime"
LABEL org.opencontainers.image.description="CoReason Runtime - Kinetic Execution Engine"

# Install Node.js substrate
# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
    nodejs \
    npm \
    && rm -rf /var/lib/apt/lists/*

# Defense-in-Depth: Create an unprivileged user to trap WASM escapes
# We use a high UID to avoid collision with host users
RUN useradd -u 10000 -m -s /bin/bash coreason && \
    mkdir -p /app/data/lancedb /app/data/plugins /app/data/bronze /app/data/silver /app/data/gold && \
    chown -R coreason:coreason /app

WORKDIR /app

# Copy the pre-built environment from the builder
# Multi-stage copy ensures we don't carry over uv or build artifacts
COPY --from=builder --chown=coreason:coreason /app/.venv /app/.venv
COPY --from=builder --chown=coreason:coreason /app/src /app/src

# Ensure the virtualenv is on the PATH
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONPATH="/app/src"
# Force Python to not write .pyc files in production to save space/entropy
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Drop root privileges
USER coreason

# Boot the API Edge by default
ENTRYPOINT ["coreason"]
CMD ["start", "api", "--port", "8000"]
