# syntax=docker/dockerfile:1.4
# Stage 1: Build & Dependency Resolution
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder

WORKDIR /app

ENV UV_COMPILE_BYTECODE=1
ENV UV_LINK_MODE=copy

# Install project dependencies
COPY pyproject.toml README.md ./
COPY hyperrr/ hyperrr/
COPY extensions/ extensions/

RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev --no-editable || uv pip install --system -e .

# Stage 2: Final Minimal Runtime Image
FROM python:3.12-slim-bookworm AS runner

WORKDIR /app

# Security: Create non-root system user
RUN groupadd -g 10001 hyperrr && \
    useradd -u 10001 -g hyperrr -s /bin/bash -m appuser

# Install curl/libpq runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    libpq5 \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY --chown=appuser:hyperrr . /app

USER appuser

ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONPATH=/app
ENV PATH="/usr/local/bin:$PATH"

EXPOSE 8000

# Built-in Healthcheck against /health/live
HEALTHCHECK --interval=15s --timeout=5s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8000/health/live || exit 1

# Default execution: Serve HTTP API
CMD ["hyperrr", "serve", "--host", "0.0.0.0", "--port", "8000"]
