# syntax=docker/dockerfile:1

# ---------- stage 1: build. Has uv; installs the dependencies into /app/.venv ----------
FROM python:3.12-slim-bookworm AS builder
COPY --from=ghcr.io/astral-sh/uv:0.11.32 /uv /uvx /bin/

ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=0

WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev

COPY . /app

# ---------- stage 2: run. Only Python, the .venv and the code; no uv, no build cache ----------
FROM python:3.12-slim-bookworm

RUN groupadd --system --gid 999 app \
 && useradd --system --gid 999 --uid 999 --no-create-home app \
 && mkdir /data && chown app:app /data

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

# The database and the log go to /data: mount a volume there so keys and usage survive a new container.
ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    GATEWAY_DB=/data/gateway.db \
    LOG_FILE=/data/gateway.log

WORKDIR /app
USER app
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=2)"]

# One worker: rate limits, breakers and the cache live in this process's memory.
CMD ["uvicorn", "--factory", "app:create_app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "30"]
