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

WORKDIR /app

RUN pip install --upgrade pip --no-cache-dir

# hatchling reads pyproject.toml, the readme it points at, and the package
# itself to generate metadata — all three must be present before installing.
COPY pyproject.toml README.md ./
COPY flowagent/ ./flowagent/

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

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

# Install curl for healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd -g 1001 appgroup && \
    useradd -u 1001 -g appgroup -m -s /bin/bash appuser

WORKDIR /app

COPY --from=builder /install /usr/local
COPY flowagent/ ./flowagent/

RUN chown -R appuser:appgroup /app

USER appuser

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

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