# Use the official Python 3.11 image as builder
FROM python:3.11-slim AS builder

# Set working directory
WORKDIR /app

# Enable BuildKit cache for apt and install build dependencies
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
    apt-get update && apt-get install -y --no-install-recommends \
    build-essential

# Create virtual environment
RUN python -m venv /app/venv
ENV PATH="/app/venv/bin:$PATH"

# Copy requirements files separately to maximize layer caching
COPY requirements/requirements-base.txt ./requirements/
COPY requirements.txt .

# Upgrade pip and install dependencies using cache mounts
# This avoids redownloading the huge 5.9GB virtualenv every time
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --upgrade pip && \
    pip install -r requirements/requirements-base.txt && \
    pip install -r requirements.txt
    


# ---------- Runtime Stage ----------
FROM python:3.11-slim AS runtime

# Install runtime tools (like make if needed)
RUN apt-get update && apt-get install -y --no-install-recommends \
    make \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

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

# Set PATH to use virtualenv
ENV PATH="/app/venv/bin:$PATH"

# Copy application files
COPY . /app/

# Optional: Add custom bash configuration
RUN echo "# Custom configurations added by Dockerfile" >> /root/.bashrc && \
    echo "export APP_PATH=/app" >> /root/.bashrc && \
    echo "alias ll='ls -la'" >> /root/.bashrc && \
    echo "PASSWORD=\"Aimo@2024\"" >> /root/.bashrc && \
    echo "echo -n \"Enter password to access container: \"" >> /root/.bashrc && \
    echo "read -s input_password" >> /root/.bashrc && \
    echo "echo \"\"" >> /root/.bashrc && \
    echo "if [ \"\$input_password\" != \"\$PASSWORD\" ]; then" >> /root/.bashrc && \
    echo "    echo \"Access denied!\"" >> /root/.bashrc && \
    echo "    exit 1" >> /root/.bashrc && \
    echo "fi" >> /root/.bashrc && \
    echo "cd /app" >> /root/.bashrc

# Expose port
EXPOSE 3021

# Default command
CMD ["python", "run.py"]
