# Multi-stage build: frontend (Vite) + backend (FastAPI)

# Frontend build
FROM node:18-bullseye-slim AS front-build
WORKDIR /frontend
ENV NODE_ENV=production NODE_OPTIONS=--max_old_space_size=1536 NPM_CONFIG_PRODUCTION=false
COPY frontend/package.json ./
RUN npm config set legacy-peer-deps true \
    && npm config set fund false \
    && npm config set audit false \
    && rm -f package-lock.json \
    && npm install --no-fund --no-audit --include=dev \
    && npm install @esbuild/linux-x64@0.21.5 --no-fund --no-audit || true \
    && npm install @rollup/rollup-linux-x64-gnu --no-fund --no-audit || true \
    && chmod -R +x node_modules/.bin \
    && chmod -R +x node_modules/vite/bin || true
COPY frontend/ .
RUN node --max_old_space_size=1536 node_modules/vite/bin/vite.js build

# Backend runtime
FROM python:3.11-slim-bookworm AS app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 PIP_DEFAULT_TIMEOUT=600

WORKDIR /app

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

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

COPY backend/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --prefer-binary --default-timeout=600 -r /app/requirements.txt

COPY backend/ /app/backend/
COPY --from=front-build /frontend/dist /app/frontend-dist

EXPOSE 8021
CMD ["uvicorn", "backend.app.main:app", "--host", "0.0.0.0", "--port", "8021"]
