FROM python:3.12-slim AS builder

WORKDIR /build

RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --upgrade pip && \
    pip wheel --no-cache-dir --wheel-dir /build/wheels -r requirements.txt


FROM python:3.12-slim AS runtime

RUN groupadd -r appuser && useradd -r -g appuser appuser

WORKDIR /app

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

COPY --from=builder /build/wheels /wheels
RUN pip install --no-cache-dir --no-index --find-links=/wheels /wheels/* \
    && rm -rf /wheels

COPY app/__init__.py        ./app/__init__.py
COPY app/main.py            ./app/main.py
COPY app/auth.py            ./app/auth.py
COPY app/database.py        ./app/database.py
COPY app/models.py          ./app/models.py
COPY app/routers/__init__.py    ./app/routers/__init__.py
COPY app/routers/stores.py      ./app/routers/stores.py
COPY app/routers/documents.py   ./app/routers/documents.py
COPY app/routers/admin.py         ./app/routers/admin.py
COPY app/routers/openai_compat.py   ./app/routers/openai_compat.py
COPY app/utils/__init__.py   ./app/utils/__init__.py
COPY app/utils/stats.py      ./app/utils/stats.py
COPY app/utils/chunking.py            ./app/utils/chunking.py
COPY app/utils/image_processor.py     ./app/utils/image_processor.py

RUN find /app -type f | sort

RUN chown -R appuser:appuser /app
USER appuser

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

EXPOSE 8000

CMD ["uvicorn", "app.main:app", \
     "--host", "0.0.0.0", \
     "--port", "8000", \
     "--workers", "4", \
     "--loop", "uvloop", \
     "--http", "httptools"]
