# Base image
FROM nvidia/cuda:12.8.0-cudnn-devel-ubuntu22.04

# Set environment variables to prevent interactive prompts and improve Python/uv behavior
ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHON_VERSION=3.12
ENV PYTHONUNBUFFERED=1
ENV UV_SYSTEM_PYTHON=1

# Install system dependencies for Python, uv, and common tools
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    software-properties-common \
    curl \
    ca-certificates \
    gnupg \
    build-essential \
    autotools-dev \
    libssl-dev \
    zlib1g-dev \
    libbz2-dev \
    libreadline-dev \
    libsqlite3-dev \
    wget \
    llvm \
    libncurses5-dev \
    libncursesw5-dev \
    xz-utils \
    tk-dev \
    libffi-dev \
    liblzma-dev \
    python3-openssl \
    git && \
    rm -rf /var/lib/apt/lists/*

# Install Python 3.12 from source
RUN wget "https://www.python.org/ftp/python/${PYTHON_VERSION}.0/Python-${PYTHON_VERSION}.0.tgz" && \
    tar -xvf "Python-${PYTHON_VERSION}.0.tgz" && \
    cd "Python-${PYTHON_VERSION}.0" && \
    ./configure --enable-optimizations --with-ensurepip=install && \
    make -j$(nproc) && \
    make altinstall && \
    cd / && \
    rm -rf "/Python-${PYTHON_VERSION}.0.tgz" "/Python-${PYTHON_VERSION}.0"

# Verify Python installation
RUN python3.12 --version

# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Verify uv installation
RUN uv --version

# Set python3.12 and pip3.12 as the default python and pip
RUN update-alternatives --install /usr/bin/python python /usr/local/bin/python3.12 1 && \
    update-alternatives --install /usr/bin/pip pip /usr/local/bin/pip3.12 1

# Set up the working directory
WORKDIR /app

ADD . /app

# Install dependencies
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project

# Sync the project
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked

# Create an output directory for files generated by your application
RUN mkdir -p /app/saves
# Declare /app/outputs as a volume. You can mount a host directory here.
VOLUME /app/saves

# Define the main executable for the container
ENTRYPOINT ["uv", "run", "finetune"]

# (Optional) Define default arguments for the ENTRYPOINT.
# These would be used if 'command' is not specified in docker-compose.yml or docker run.
# For example:
# CMD ["pipeline=default_processing", "hydra.run.dir=/app/outputs/default_run"]

# Reset DEBIAN_FRONTEND to its default
ENV DEBIAN_FRONTEND=dialog
