# Backend API Dockerfile
# Multi-stage: keep runtime image small and predictable.
# ARM64-friendly (works on Apple Silicon and AWS Graviton).

FROM python:3.14-slim@sha256:6a27522252aef8432841f224d9baaa6e9fce07b07584154fa0b9a96603af7456 AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_NO_CACHE_DIR=1 \
    VIRTUAL_ENV=/opt/venv

# Build deps only (not shipped in final image).
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    curl \
    libpq-dev \
    libffi-dev \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /build

RUN python -m venv "${VIRTUAL_ENV}"
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"

COPY apps/backend/requirements.runtime.txt ./requirements.runtime.txt

RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --upgrade pip && \
    pip install -r requirements.runtime.txt


FROM python:3.14-slim@sha256:6a27522252aef8432841f224d9baaa6e9fce07b07584154fa0b9a96603af7456 AS runtime

LABEL maintainer="workweaver-prod"
LABEL description="Backend API for Workweaver"

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    VIRTUAL_ENV=/opt/venv

# Runtime deps (keep minimal).
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    libpq5 \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder "${VIRTUAL_ENV}" "${VIRTUAL_ENV}"
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"

# Set working directory to repository root inside the image.
WORKDIR /usr/src/app

# Copy backend, shared code, admin portal SPA, and canonical Zoho registry seed from the repository root context.
# apps/admin-portal was deleted in #869 phase 1 (dead app cleanup).
# The admin portal SPA now lives at apps/landing/public/admin/ and is copied
# into the expected apps/admin-portal/ path for backward compatibility with
# main.py's _ADMIN_PORTAL_DIR reference.
RUN mkdir -p apps/backend apps/admin-portal skills/zoho-cli
COPY --chmod=755 apps/backend/ ./apps/backend/
COPY --chmod=755 apps/shared/ ./apps/shared/
COPY --chmod=644 apps/landing/public/admin/ ./apps/admin-portal/
COPY --chmod=644 skills/zoho-cli/registry.json ./skills/zoho-cli/registry.json

# Set PYTHONPATH to include the repository-root package layout.
ENV PYTHONPATH=/usr/src/app:/usr/src/app/apps/backend

# Create non-root user.
RUN groupadd -r apiuser && useradd -r -g apiuser apiuser && \
    chown -R apiuser:apiuser /usr/src/app

USER apiuser
WORKDIR /usr/src/app/apps/backend

EXPOSE 8000

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

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
