# Use a multi-stage build for smaller image size
FROM python:3.12-slim-bookworm as builder

WORKDIR /app

# Install build dependencies
# curl/git might be needed for installing uv or dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    git \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Install uv for fast package management
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv

# Copy dependency files
COPY pyproject.toml uv.lock ./

# Install dependencies into a virtual environment
# We use --frozen to ensure we use exactly what's in uv.lock
RUN uv sync --frozen --no-dev --no-install-project

# Runtime stage
FROM python:3.12-slim-bookworm

WORKDIR /app

# Install runtime dependencies (e.g. curl for healthcheck)
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy the virtual environment from the builder stage
COPY --from=builder /app/.venv /app/.venv

# Enable the virtual environment
ENV PATH="/app/.venv/bin:$PATH"

# Copy application code
COPY src ./src
COPY deploy ./deploy
COPY README.md ./

# Create a non-root user
RUN useradd -m tiphys && chown -R tiphys:tiphys /app
USER tiphys

# Create data directory
RUN mkdir -p /home/tiphys/.tiphys/sessions /home/tiphys/.tiphys/logs /home/tiphys/.tiphys/tasks

# Expose port
EXPOSE 8000

# Set environment variables
ENV TIPHYS_HOST=0.0.0.0
ENV TIPHYS_PORT=8000

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

# Entry point
ENV PYTHONPATH=/app/src

CMD ["python", "-m", "tiphys.main", "gateway"]
