# === Builder stage ===
FROM python:3.11-slim AS builder

WORKDIR /build

RUN pip install --no-cache-dir uv

COPY pyproject.toml .
COPY src/ src/

# Install production dependencies only (no dev extras)
RUN uv pip install --system --no-cache "." \
    && uv pip install --system --no-cache ".[embedding]"

# === Runtime stage ===
FROM python:3.11-slim

WORKDIR /app

# Install curl for healthcheck
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -r tmh && useradd -r -g tmh -u 1000 -m tmh

# Copy installed packages from builder
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy source code
COPY src/ src/
COPY pyproject.toml .
COPY tmh.toml.example tmh.toml
COPY main.py .

# Create data directory with correct ownership
RUN mkdir -p /app/data && chown -R tmh:tmh /app/data /app/tmh.toml

# Switch to non-root user
USER tmh

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8000/api/v1/health || exit 1

CMD ["uvicorn", "team_memory_hub.server.app:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
