FROM python:3.12-slim AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    UV_LINK_MODE=copy

WORKDIR /app


RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libpq-dev \
    curl \
    openssh-client \
    git \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Install Node 22 + pnpm
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
    && apt-get update \
    && apt-get install -y --no-install-recommends nodejs \
    && corepack enable \
    && corepack prepare pnpm@latest --activate \
    && rm -rf /var/lib/apt/lists/*

RUN curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:${PATH}"

# Install dependencies first (cached layer — only invalidated when lockfile changes)
COPY pyproject.toml uv.lock ./

# Add key from git.envipath.com to known_hosts
RUN mkdir -p -m 0700 /root/.ssh \
    && ssh-keyscan git.envipath.com >> /root/.ssh/known_hosts

# We'll need access to private repos, let docker make use of host ssh agent and use it like:
# docker build --ssh default -t envipath/envipy:1.0 .
RUN --mount=type=ssh \
    uv sync --locked --extra pepper-plugin

# Now copy source and do a final sync to install the project itself
# Ensure .dockerignore is reasonable
COPY biotransformer biotransformer
COPY bridge bridge
COPY envipath envipath
COPY epapi epapi
COPY epauth epauth
COPY epdb epdb
COPY epiuclid epiuclid
COPY fixtures fixtures
COPY migration migration
COPY pepper pepper
COPY scripts scripts
COPY static static
COPY templates templates
COPY tests tests
COPY utilities utilities
COPY manage.py .

# Used to run migrations etc
COPY entrypoint.sh entrypoint.sh
RUN chmod +x entrypoint.sh

# Install frontend deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./

# Build frontend assets
RUN uv run python scripts/pnpm_wrapper.py install
RUN uv run python scripts/pnpm_wrapper.py run build

FROM python:3.12-slim AS production

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PATH="/app/.venv/bin:$PATH"

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends \
    libpq5 \
    libxrender1 \
    libxext6 \
    libfontconfig1 \
    nano \
    && rm -rf /var/lib/apt/lists/*

RUN useradd -ms /bin/bash django

# Create directories in /opt and set ownership
RUN mkdir -p /opt/enviPy \
    && mkdir -p /opt/enviPy/celery \
    && mkdir -p /opt/enviPy/log \
    && mkdir -p /opt/enviPy/models \
    && mkdir -p /opt/enviPy/plugins \
    && mkdir -p /opt/enviPy/static \
    && chown -R django:django /opt/enviPy

COPY --from=builder --chown=django:django /app /app

RUN touch /app/.env && chown -R django:django /app/.env

USER django

EXPOSE 8000

ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["gunicorn", "envipath.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "8"]
