# Multi-stage build, non-root runtime user, healthcheck — same pattern as
# deploy/docker/Dockerfile (the existing Private Deployment image), kept
# consistent rather than inventing a second convention for the same repo.

# ---- Builder ------------------------------------------------------------------
FROM python:3.12-slim AS builder

WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential \
    && rm -rf /var/lib/apt/lists/*

COPY pyproject.toml README.md ./
COPY app/ ./app/
COPY main.py ./
RUN pip install --no-cache-dir --target=/build/deps .

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

RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
    && rm -rf /var/lib/apt/lists/*

RUN useradd --create-home --uid 1000 meridian

WORKDIR /app
COPY --from=builder /build/deps /usr/local/lib/python3.12/site-packages
# `pip install --target=X` splits an install in two: libraries land in X, but
# console scripts land in X/bin. Copying only the former gives an image where
# uvicorn imports fine and `uvicorn` is still "not found" — which is exactly
# how this failed its first deploy. Needed for one-off commands too: running
# migrations is `alembic upgrade head`, another script from this directory.
COPY --from=builder /build/deps/bin /usr/local/bin
COPY app/ ./app/
COPY main.py ./

ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

USER meridian
EXPOSE 8080

# $PORT, defaulting to 8080. Hosting platforms (Railway, Fly, Render, Cloud
# Run) assign a port at runtime and route to that one only; a container that
# hardcodes 8080 listens where nothing is looking and the deploy fails its
# health check with no error in the application log. Shell form is required
# for the variable to be expanded at all — exec form would pass the literal
# string "${PORT:-8080}" to uvicorn.
ENV PORT=8080

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import os,urllib.request,sys; sys.exit(0 if urllib.request.urlopen(f\"http://localhost:{os.environ.get('PORT','8080')}/health\", timeout=3).status == 200 else 1)" || exit 1

#
# `python -m uvicorn` rather than the `uvicorn` script: it resolves through
# the interpreter's own import path, so the container still starts even if
# the scripts directory above is ever missing or off PATH.
CMD ["sh", "-c", "exec python -m uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}"]
