# syntax=docker/dockerfile:1

# ---- build the project and all dependencies into wheels -------------------------------------
FROM python:3.12-slim AS builder
WORKDIR /build
COPY pyproject.toml ./
COPY src ./src
RUN pip wheel --no-cache-dir --wheel-dir /wheels .

# ---- runtime image -------------------------------------------------------------------------
FROM python:3.12-slim AS runtime

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

RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app

WORKDIR /app

COPY --from=builder /wheels /wheels
RUN pip install --no-index --find-links /wheels estimator && rm -rf /wheels

# The service reads these relative to its working directory: config/ (TOML and market data),
# prompts/ (the model prompts), and migrations/ with alembic.ini (the schema).
COPY --chown=app:app config ./config
COPY --chown=app:app prompts ./prompts
COPY --chown=app:app migrations ./migrations
COPY --chown=app:app alembic.ini ./
COPY --chown=app:app docker/entrypoint.sh ./docker/entrypoint.sh
RUN chmod 0755 /app/docker/entrypoint.sh

USER app
EXPOSE 8000

HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=3 \
  CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health' % os.environ.get('EST_API__PORT', '8000'), timeout=4)"]

ENTRYPOINT ["/app/docker/entrypoint.sh"]
CMD ["serve"]
