## ---------- Build stage ----------
FROM python:3.12-slim AS builder

WORKDIR /build

RUN pip install --no-cache-dir hatchling

COPY pyproject.toml README.md ./
COPY app/ app/

RUN pip install --no-cache-dir --prefix=/install .

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

WORKDIR /app

# Security: run as non-root
RUN groupadd -r appuser && useradd -r -g appuser appuser

COPY --from=builder /install /usr/local
COPY alembic.ini ./
COPY alembic/ alembic/
COPY app/ app/

RUN chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD python -c "import httpx; httpx.get('http://localhost:8000/health')" || exit 1

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
