# Build stage
FROM python:3.11-slim AS builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY pyproject.toml .
RUN pip install --no-cache-dir -e ".[dev]" \
    && pip wheel --no-cache-dir --wheel-dir /app/wheels \
    pydantic lancedb pyarrow requests watchdog typer rich numpy httpx sse-starlette fastapi uvicorn

# Production stage
FROM python:3.11-slim AS production

WORKDIR /app

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    && rm -rf /var/lib/apt/lists/*

# Copy wheels and install
COPY --from=builder /app/wheels /wheels
RUN pip install --no-cache-dir /wheels/*

# Copy application code
COPY companion/ ./companion/
COPY companion/forge/ ./companion/forge/
COPY companion/indexer_daemon/ ./companion/indexer_daemon/
COPY companion/rag/ ./companion/rag/

# Create directories for data
RUN mkdir -p /data/vectors /data/memory /models

# Copy default config
COPY config.json /app/config.json

# Environment variables
ENV PYTHONPATH=/app
ENV COMPANION_CONFIG=/app/config.json
ENV COMPANION_DATA_DIR=/data

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import requests; requests.get('http://localhost:7373/health')" || exit 1

# API port
EXPOSE 7373

# Default command
CMD ["python", "-m", "uvicorn", "companion.api:app", "--host", "0.0.0.0", "--port", "7373"]
