# ▲ Serial Alice Agent — Docker Image
# Multi-stage build: deps + runtime

# ── Stage 1: Builder ─────────────────────────────────────────────────────────
FROM python:3.12-slim AS builder

WORKDIR /build

# Install build deps
RUN pip install --no-cache-dir build wheel

# Copy agent source
COPY pyproject.toml ./
COPY *.py ./
COPY machine/ machine/
COPY hardware/ hardware/
COPY runtime/ runtime/
COPY telemetry/ telemetry/
COPY energy/ energy/
COPY attestation/ attestation/
COPY client/ client/
COPY __init__.py ./

# Build wheel
RUN python -m build --wheel --no-isolation -o /dist .

# ── Stage 2: Runtime ─────────────────────────────────────────────────────────
FROM python:3.12-slim AS runtime

LABEL maintainer="Sirius GreenTech <contact@siriusgreentech.pt>"
LABEL description="▲ Serial Alice Agent — Verifiable Energy for Compute"
LABEL version="1.0.0"

# Install psutil and pynvml
# pynvml requires NVIDIA drivers mounted at /dev (--gpus flag or nvidia-docker)
RUN pip install --no-cache-dir psutil pyyaml pynvml && \
    rm -rf /root/.cache/pip

# Copy wheel and install
COPY --from=builder /dist/*.whl /tmp/
RUN pip install --no-cache-dir /tmp/*.whl && rm /tmp/*.whl

# Create agent user and directories
RUN useradd --system --no-create-home --shell /sbin/nologin serial-alice-agent && \
    mkdir -p /etc/serial-alice-agent /var/lib/serial-alice-agent /var/log/serial-alice-agent && \
    chown serial-alice-agent:serial-alice-agent \
          /var/lib/serial-alice-agent /var/log/serial-alice-agent

# Copy default config
COPY config.yaml.example /etc/serial-alice-agent/config.yaml.example

# Runtime env defaults
ENV SA_AGENT_LOG_LEVEL=INFO \
    SA_AGENT_WORKSPACE=/var/lib/serial-alice-agent

# Non-root by default
USER serial-alice-agent

# Prometheus metrics port
EXPOSE 9091

# Healthcheck
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
    CMD serial-alice-agent status || exit 1

ENTRYPOINT ["serial-alice-agent"]
CMD ["start"]
