# syntax=docker/dockerfile:1.7
# Cyclone backend — FastAPI on uvicorn.
#
# Image layout:
#   /app                   repo root (copied by docker-compose)
#   /app/backend/src       python package source
#   /app/config            config/payers.yaml lives here
#   /data                  persistent SQLite volume mountpoint
#
# Build context for this Dockerfile is the repo root (../) when invoked
# from docker-compose, so paths below are relative to repo root.

FROM python:3.11-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# curl is used by the HEALTHCHECK. build-essential is not required — the
# backend is pure-python wheels on linux/amd64 + linux/arm64.
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Non-root user. UID 10001 is unlikely to collide with the host UID.
RUN groupadd --system --gid 10001 cyclone \
    && useradd  --system --uid 10001 --gid cyclone --home /app --shell /usr/sbin/nologin cyclone

WORKDIR /app

# Source + YAML config. Tests + fixtures + prodfiles are intentionally
# excluded from the runtime image (see backend/.dockerignore).
COPY backend/src /app/backend/src
COPY config      /app/config

# Install deps last so source changes don't bust the pip cache layer.
# `pip install -e .` needs the `src/cyclone` package directory to exist
# at install time (setuptools runs egg-info during the editable install),
# so the source COPY above must come first.
COPY backend/pyproject.toml backend/uv.lock* /app/backend/
RUN pip install --no-cache-dir -e /app/backend

# Persistent volume mountpoint. SQLite needs the directory to exist and
# to be writable by the cyclone user; Docker creates the volume but the
# directory inside the image must be pre-created with the right owner.
RUN mkdir -p /data && chown -R cyclone:cyclone /data

USER cyclone

ENV CYCLONE_HOST=0.0.0.0 \
    CYCLONE_PORT=8000 \
    CYCLONE_RELOAD=0 \
    CYCLONE_DB_URL=sqlite:////data/cyclone.db \
    PYTHONPATH=/app/backend/src

EXPOSE 8000

HEALTHCHECK --interval=15s --timeout=5s --start-period=10s --retries=3 \
    CMD curl --fail --silent http://127.0.0.1:8000/api/health || exit 1

# `python -m cyclone serve` honors CYCLONE_HOST/CYCLONE_PORT/CYCLONE_RELOAD
# from the env above. PYTHONPATH puts the editable package on the path.
CMD ["python", "-m", "cyclone", "serve"]