FROM python:3.12-slim

WORKDIR /app

# Install uv (faster, better dependency resolution)
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Install system dependencies (switch apt to Aliyun mirror for CI runners in China)
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources \
    && apt-get update && apt-get install -y --no-install-recommends \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r kbox && useradd -r -g kbox kbox

# PyPI mirror for CI runners in China (uv.lock hashes are content-based, mirror-safe);
# override with --build-arg PIP_INDEX_URL=https://pypi.org/simple/ if needed
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/
ENV UV_DEFAULT_INDEX=${PIP_INDEX_URL} \
    UV_HTTP_TIMEOUT=300 \
    UV_CONCURRENT_DOWNLOADS=8

# Copy dependency files for layer caching
COPY pyproject.toml uv.lock ./

# Install Python dependencies only (not the project, for Docker layer caching)
RUN uv sync --frozen --no-dev --no-install-project

# Copy application code
COPY kbox_connectors ./kbox_connectors
COPY skills ./skills
COPY README.md ./

# Install the project itself (non-editable)
RUN uv sync --frozen --no-dev --no-editable

# Change ownership
RUN chown -R kbox:kbox /app

# Switch to non-root user
USER kbox

# Use project venv
ENV PATH="/app/.venv/bin:$PATH"

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \
    CMD curl -f http://localhost:8082/health || exit 1

# Expose port
EXPOSE 8082

# Run application
CMD ["python", "-m", "kbox_connectors.server"]
