# Use the latest Python image as the base image
FROM python:latest

# Set environment variables
ENV PYTHONUNBUFFERED=1 \
    HOME=/home/user \
    PATH=/home/user/.local/bin:/home/user/venv/bin:$PATH

# Expose the port that the server will run on
EXPOSE 7860

# Update the package list and upgrade existing packages
RUN apt-get update && apt-get upgrade -y

# Install required packages
RUN apt-get install -y curl wget neofetch ffmpeg \
    libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libgbm1 libasound2 libpangocairo-1.0-0 libxss1 libgtk-3-0 imagemagick \
    python3 python3-pip python3-venv build-essential libvips libvips-dev libjpeg-dev libpng-dev

# Add NodeSource APT repository for Node 18.x
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -

# Install Node.js and npm
RUN apt-get install -y nodejs

# Create a non-root user and switch to it
RUN useradd -m -u 1000 user

# Set the working directory
WORKDIR /home/user/app

# Copy package.json and package-lock.json files and install dependencies before switching to the non-root user
COPY package*.json ./
RUN npm install && \
    npm install -g npm@latest node-gyp nodemon

RUN npm i github:ArashiCode/duo-canvas
RUN npm i sharp@latest

# Switch to the non-root user
USER user

# Create and activate a virtual environment in the user's home directory
RUN python3 -m venv /home/user/venv

# Install speedtest-cli within the virtual environment
RUN /home/user/venv/bin/pip install --no-cache-dir speedtest-cli

# Copy the rest of the application code
COPY --chown=user . .

# Start the application
CMD ["npm", "start"]