# BEMServer - Building Energy Management Server
# Multi-component Dockerfile: core + api + ui + celery
# Based on Python 3.11 slim with TimescaleDB support

FROM python:3.11-slim AS base

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

WORKDIR /opt/bemserver

# ---- Stage 1: Install bemserver-core ----
FROM base AS core
COPY bemserver/bemserver-core /tmp/bemserver-core
RUN pip install --no-cache-dir /tmp/bemserver-core

# ---- Stage 2: Install bemserver-api ----
FROM core AS api
COPY bemserver/bemserver-api /tmp/bemserver-api
RUN pip install --no-cache-dir /tmp/bemserver-api

# ---- Stage 3: Install bemserver-ui ----
FROM api AS ui
COPY bemserver/bemserver-ui /tmp/bemserver-ui
RUN pip install --no-cache-dir /tmp/bemserver-ui

# ---- Final stage ----
FROM ui AS final

# Create non-root user
RUN groupadd -r bemserver && useradd -r -g bemserver -d /opt/bemserver -s /sbin/nologin bemserver

# Create config directory
RUN mkdir -p /opt/bemserver/config /opt/bemserver/data \
    && chown -R bemserver:bemserver /opt/bemserver

# Copy entrypoint script
COPY bemserver/entrypoint.sh /opt/bemserver/entrypoint.sh
RUN chmod +x /opt/bemserver/entrypoint.sh

# Healthcheck
HEALTHCHECK --interval=30s --timeout=10s --retries=5 --start_period=60s \
    CMD curl -f http://localhost:5000/healthz || exit 1

USER bemserver

ENTRYPOINT ["/opt/bemserver/entrypoint.sh"]
