# Dockerfile
FROM python:3.11-slim-bullseye AS base

# Update and install common packages
RUN apt-get update && apt-get install gcc curl -y libffi-dev libssl-dev

WORKDIR /var/app

# Create and configure virtualenv and uwsgi
RUN python3 -m venv env
RUN env/bin/python3 -m pip install -q -U pip setuptools wheel
RUN env/bin/python3 -m pip install -q uwsgi

# Add application code
COPY application.py requirements.txt ./
COPY charts ./charts

# Install deps
RUN env/bin/python3 -m pip install --use-pep517 -I -r requirements.txt

# deploy stage - build image for live deployment
FROM        base AS deploy

# snowflake-connector-python 4.4.0 stats ~/.snowflake at import time; Python 3.11 propagates
# PermissionError from Path.exists() when /root is inaccessible (uwsgi user). Point elsewhere.
ENV        SNOWFLAKE_HOME=/var/app/.snowflake

# Configure UWSGI
RUN        useradd uwsgi -s /bin/false
# Allow non-root users to traverse /root so Path('/root/.snowflake').exists()
# raises FileNotFoundError instead of PermissionError (Python 3.11 propagates it).
RUN        chmod o+x /root
RUN        chown uwsgi:uwsgi -R /var/app/
RUN        mkdir /var/app/.snowflake && chmod 777 /var/app/.snowflake
RUN        mkdir /var/log/uwsgi
RUN        chown -R uwsgi:uwsgi /var/log/uwsgi

# Add application and install requirements
ADD        . /var/app
RUN        if [ -f /var/app/requirements.txt ]; then pip install --use-pep517 -I -r /var/app/requirements.txt; fi

# Add startup script
ADD        uwsgi-start.sh /
RUN        chmod +x /uwsgi-start.sh
ENTRYPOINT ["/uwsgi-start.sh"]

EXPOSE     8080
