FROM python:3.13-slim

EXPOSE 8000
WORKDIR /app

ENV PATH="/app/.venv/bin:$PATH"
ENV STATIC_ROOT=/app/staticfiles
ENV MEDIA_ROOT=/data/media
# Set Caddy's XDG base directory to a writable location
ENV XDG_DATA_HOME=/app/run/caddy/data
ENV XDG_CONFIG_HOME=/app/run/caddy/config

# Install system dependencies including Caddy
RUN apt-get update && apt-get install -y \
    debian-keyring \
    debian-archive-keyring \
    apt-transport-https \
    curl \
    && curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg \
    && curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list \
    && apt-get update \
    && apt-get install -y caddy procps \
    && rm -rf /var/lib/apt/lists/*

# Install binaries with correct permissions
COPY --from=ghcr.io/astral-sh/uv:latest --chown=root:root --chmod=755 /uv /usr/local/bin/uv
COPY --chmod=755 docker/run.sh /usr/local/bin/run.sh

COPY docker/Caddyfile /app/config/caddy/Caddyfile
ADD . /app

RUN uv sync --frozen \
    && uv pip install gunicorn --no-cache-dir \
    && mkdir -p /app/config/caddy /app/run/caddy /app/run/gunicorn \
    && chgrp -R 0 /app \
    && chmod -R g=u /app \
    && chmod g+w /app/config/caddy/Caddyfile
    # && SECRET_KEY= uv run src/manage.py collectstatic --noinput

CMD ["/usr/local/bin/run.sh"]