# Multi-stage build: Node compiles React frontend, Python runs backend.
# Frontend dist is baked into the image (no runtime volume mount needed).

FROM node:20-alpine AS frontend-build
WORKDIR /app/frontend/web
COPY frontend/web/package.json frontend/web/package-lock.json* ./
RUN npm config set registry https://registry.npmmirror.com && npm ci --silent
COPY frontend/web/ ./
RUN npm run build

FROM python:3.11.15-slim-bookworm AS runtime
WORKDIR /app

ARG BUILD_COMMIT=unknown
ARG BUILD_TIME=unknown
ENV AGENTEVAL_BUILD_COMMIT=${BUILD_COMMIT}
ENV AGENTEVAL_BUILD_TIME=${BUILD_TIME}

ENV PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/
ENV PIP_TRUSTED_HOST=mirrors.aliyun.com
RUN sed -i \
    -e 's|deb.debian.org|mirrors.aliyun.com|g' \
    -e 's|security.debian.org|mirrors.aliyun.com/debian-security|g' \
    /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
RUN sed -i \
    -e 's|deb.debian.org|mirrors.aliyun.com|g' \
    -e 's|security.debian.org|mirrors.aliyun.com/debian-security|g' \
    /etc/apt/sources.list 2>/dev/null || true

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

COPY pyproject.toml README.md alembic.ini ./
COPY migrations ./migrations
COPY backend ./backend

RUN pip install --no-cache-dir -e .

COPY --from=frontend-build /app/frontend/web/dist ./frontend/web/dist
COPY config/config.example.json ./config/config.json
RUN mkdir -p ./data/scenarios ./data/reports

EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD curl -f http://localhost:8000/api/health || exit 1
COPY scripts/production-entrypoint.sh ./scripts/production-entrypoint.sh
RUN chmod +x ./scripts/production-entrypoint.sh

CMD ["./scripts/production-entrypoint.sh"]
