# Stage 1: Build
FROM python:3.11-slim AS builder

WORKDIR /app

COPY pyproject.toml README.md LICENSE ./
COPY alembic.ini ./
COPY alembic/ alembic/
COPY src/ src/

RUN pip install --no-cache-dir build && python -m build --wheel

# Stage 2: Runtime
FROM python:3.11-slim

WORKDIR /app

RUN groupadd -r aegis && useradd -r -g aegis -m -d /home/aegis aegis

ENV HOME=/home/aegis

COPY --from=builder /app/dist/*.whl /tmp/
COPY --from=builder /app/alembic.ini ./alembic.ini
COPY --from=builder /app/alembic ./alembic
RUN wheel_path="$(echo /tmp/aegis_eval-*.whl)" \
  && pip install --no-cache-dir "${wheel_path}[api,db]" \
  && rm /tmp/*.whl \
  && mkdir -p /home/aegis/.aegis \
  && chown -R aegis:aegis /app /home/aegis

USER aegis

EXPOSE 8000

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

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