# Stage 1:
# This stage installs build dependencies and builds Python packages into wheels.
FROM python:3.13-slim-bookworm AS builder

# Install build dependencies for rrdtool and Python packages
RUN apt-get update && apt-get install -y --no-install-recommends \
    librrd-dev \
    build-essential \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy requirements file
COPY requirements.txt .

# Install Python dependencies into a wheelhouse
# This builds source distributions (like rrdtool) into wheels
# We don't need a venv here as we're just creating wheels, not installing them
RUN pip install --no-cache-dir --upgrade pip && \
    pip wheel --no-cache-dir --wheel-dir /tmp/wheels -r requirements.txt


# Stage 2: Runtime
# This stage takes the minimal base image and copies only the necessary runtime artifacts.
FROM python:3.13-slim-bookworm

# Install runtime system dependencies for rrdtool and wget for healthcheck
# rrdtool and librrd8 are the runtime libraries for rrdtool (not librrd-dev)
RUN apt-get update && apt-get install -y --no-install-recommends \
    rrdtool \
    librrd8 \
    wget \
    # Final cleanup to reduce image size
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Set working directory
WORKDIR /app

# Create a non-root user for security (before creating venv in their home if desired, or in /opt)
RUN useradd --create-home --shell /bin/bash appuser

# Create a virtual environment for the application
# We'll put it in /opt/venv for consistency, and ensure appuser can access it
RUN python3 -m venv /opt/venv && \
    /opt/venv/bin/pip install --no-cache-dir --upgrade pip

# Copy the built Python wheels from the builder stage
COPY --from=builder /tmp/wheels /tmp/wheels/

# Install Python dependencies from the wheels into the virtual environment
RUN /opt/venv/bin/pip install --no-cache-dir /tmp/wheels/*.whl && \
    rm -rf /tmp/wheels # Remove the wheels after installation to save space

# Copy application code
COPY app/ ./app/

# Set permissions for the appuser and data directory
RUN chown -R appuser:appuser /app && \
    chown -R appuser:appuser /opt/venv && \
    mkdir -p /data && \
    chown -R appuser:appuser /data && \
    chmod 777 /data # Ensure volume mount has write permissions

# Switch to the non-root user
USER appuser

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8000/health || exit 1

# Run the application using the virtual environment's python interpreter
CMD ["/opt/venv/bin/python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"]
#CMD ["/opt/venv/bin/python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
