# Use Python 3.12 as the base image (satisfies requires-python >=3.12).
# Force the amd64 architecture to obtain an available `cadquery-ocp` wheel; Linux aarch64 has no official wheel.
FROM --platform=linux/amd64 python:3.12-slim

# Set the working directory.
WORKDIR /app

# Set environment variables.
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1
ENV DEBIAN_FRONTEND=noninteractive

RUN set -e; . /etc/os-release; \
  codename="${VERSION_CODENAME}"; \
  printf 'deb https://mirrors.ustc.edu.cn/debian/ %s main contrib non-free non-free-firmware\n' "$codename" > /etc/apt/sources.list; \
  printf 'deb https://mirrors.ustc.edu.cn/debian/ %s-updates main contrib non-free non-free-firmware\n' "$codename" >> /etc/apt/sources.list; \
  printf 'deb https://mirrors.ustc.edu.cn/debian-security %s-security main contrib non-free non-free-firmware\n' "$codename" >> /etc/apt/sources.list; \
  printf 'deb https://mirrors.ustc.edu.cn/debian/ %s-backports main contrib non-free non-free-firmware\n' "$codename" >> /etc/apt/sources.list

# Install system dependencies, including OpenGL runtime libraries for libGL.so.1.
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    git \
    # OpenGL/GLX/EGL runtime libraries commonly needed by VTK/Qt/pyvista.
    libgl1 \
    libglib2.0-0 \
    libsm6 \
    libxext6 \
    libxrender1 \
    libglu1-mesa \
    libglx-mesa0 \
    libegl1 \
    # Headless rendering with Xvfb.
    xvfb \
    xauth \
    libx11-6 \
    libxkbcommon0 \
    fonts-dejavu-core \
    && rm -rf /var/lib/apt/lists/*

ENV TMPDIR=/app/tmp
RUN mkdir -p /app/tmp && chmod 1777 /app/tmp


# Copy only exported requirements to maximize layer caching.
COPY requirements.txt ./

# requirements.txt is automatically exported from uv.lock in pre-commit.
RUN export PIP_INDEX_URL="https://mirrors.ustc.edu.cn/pypi/web/simple" \
    && pip install --no-cache-dir -r requirements.txt

ENV DISPLAY=:99
ENV PYVISTA_OFF_SCREEN=true
ENV PYVISTA_USE_PANEL=false
ENV QT_QPA_PLATFORM=offscreen
ENV MPLBACKEND=Agg
ENV LIBGL_ALWAYS_SOFTWARE=1

# Copy project files.
COPY . .

# Create required directories.
RUN mkdir -p /app/data /app/logs /app/workspace

# Set permissions.
RUN chmod +x /app/start_caddesigner_api.py

# Copy and configure the entrypoint script to provide Xvfb headless rendering for the API service.
COPY docker/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

# Expose the API port.
EXPOSE 8000

# The entrypoint script starts Xvfb and then executes the final command.
ENTRYPOINT ["/app/entrypoint.sh"]
# Start the API by default.
