# D-H8: base image pinned by digest, not a mutable tag.
FROM python:3.12-slim@sha256:5b5fe805d367f8f5a359ded6ab2652b7f9a206453ee6ee789c0045ba6ec15016 AS base

# Install system dependencies
RUN apt-get update && \
    apt-get install --no-install-recommends -y build-essential git libportaudio2 pandoc wget fonts-unifont fontconfig  && \
    wget -O /tmp/fonts-ubuntu.deb https://deb.debian.org/debian/pool/non-free/f/fonts-ubuntu/fonts-ubuntu_0.83-6_all.deb && \
    wget -O /tmp/ttf-unifont.deb https://deb.debian.org/debian/pool/main/u/unifont/ttf-unifont_13.0.06-1_all.deb && \
    wget -O /tmp/ttf-ubuntu-font-family.deb https://deb.debian.org/debian/pool/non-free/f/fonts-ubuntu/ttf-ubuntu-font-family_0.83-4_all.deb && \
    echo "bd16170cba3b70e2a81506c947716b22e3781c321a20b64aeef4e786876577c9  /tmp/fonts-ubuntu.deb" | sha256sum -c - && \
    echo "26c8ddafbe8cbee2b384198839baf9dc770beb8715396e14c4476e8dab38e859  /tmp/ttf-unifont.deb" | sha256sum -c - && \
    echo "c00e9d8db71fe80b0808ec4b01951739feb28ce96829e4d2d80a700dfcdc5658  /tmp/ttf-ubuntu-font-family.deb" | sha256sum -c - && \
    dpkg -i /tmp/fonts-ubuntu.deb /tmp/ttf-unifont.deb /tmp/ttf-ubuntu-font-family.deb && \
    apt-get install -f -y && \
    rm /tmp/fonts-ubuntu.deb /tmp/ttf-unifont.deb /tmp/ttf-ubuntu-font-family.deb && \
    fc-cache -fv && \
    rm -rf /var/lib/apt/lists/* && \    
    rm -rf /var/lib/apt/lists/*

# Create app user with UID 1000
RUN useradd -m -u 1000 -s /bin/bash appuser

WORKDIR /app

# Create virtual environment
RUN python -m venv /venv
ENV PATH="/venv/bin:$PATH"
RUN /venv/bin/python -m pip install --no-cache-dir uv==0.13.10

# Create directories with proper permissions
RUN mkdir -p /home/appuser/.cecli /home/appuser/.cache && \
    chown -R appuser:appuser /home/appuser /app /venv && \
    chmod -R 755 /home/appuser/.cecli /home/appuser/.cache

# So git doesn't complain about unusual permissions
RUN git config --system --add safe.directory /app

# This puts the container's ~/.cecli into the host's project directory (usually host's cwd).
# That way caches, version checks, etc get stored in the host filesystem not
# simply discarded every time the container exits.
ENV HOME=/app

#########################
FROM base AS cecli

ENV CECLI_DOCKER_IMAGE=dustinwashington/cecli

# Copy requirements files
COPY requirements.txt /tmp/cecli/
COPY requirements/ /tmp/cecli/requirements/

# Install dependencies as root
RUN uv pip install --no-cache-dir -r /tmp/cecli/requirements.txt && \
    rm -rf /tmp/cecli

# Fix site-packages permissions (readable/executable, never world-writable)
RUN find /venv/lib/python3.12/site-packages \( -type d -exec chmod a+rx {} + \) -o \( -type f -exec chmod a+r {} + \)

# Copy the rest of the application code
COPY . /app/

# Install the application as a package
RUN uv pip install . && \
    find . -mindepth 1 -delete

# Switch to appuser
USER appuser

ENTRYPOINT ["/venv/bin/cecli"]
