# Build stage: clone and install Hermes Agent + WebUI dependencies
FROM python:3.14-slim AS builder

WORKDIR /build

# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/*

# Install uv system-wide
# hadolint ignore=DL4006
RUN curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh

# Clone Hermes Agent at a pinned commit
ARG HERMES_AGENT_VERSION=v2026.6.5
RUN git clone --depth 1 --branch ${HERMES_AGENT_VERSION} \
    https://github.com/NousResearch/hermes-agent.git /build/hermes-agent

# Clone Hermes WebUI at a pinned commit
ARG HERMES_WEBUI_VERSION=v0.51.350
RUN git clone --depth 1 --branch ${HERMES_WEBUI_VERSION} \
    https://github.com/nesquena/hermes-webui.git /build/hermes-webui

# Create a shared venv and install both projects
# hadolint ignore=DL3059
RUN uv venv /build/venv
ENV VIRTUAL_ENV=/build/venv
ENV PATH="/build/venv/bin:$PATH"

# Install hermes-agent with all extras (includes ML/agent deps)
# hadolint ignore=DL3013,DL3059
RUN uv pip install \
    "/build/hermes-agent[all]"

# Install hermes-webui deps (pyyaml + cryptography)
# hadolint ignore=DL3059
RUN uv pip install \
    -r /build/hermes-webui/requirements.txt

# Install uv in the venv so the webui server can use it for profile/skill management
# hadolint ignore=DL3059
RUN uv pip install \
    "uv>=0.6.0"

# Runtime stage
FROM python:3.14-slim

WORKDIR /app

# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    git \
    openssh-client \
    && rm -rf /var/lib/apt/lists/*

# Copy the virtual environment and source trees from builder
COPY --from=builder /build/venv /opt/venv
COPY --from=builder /build/hermes-agent /opt/hermes-agent
COPY --from=builder /build/hermes-webui /app

# Set environment
ENV PATH="/opt/venv/bin:$PATH" \
    VIRTUAL_ENV=/opt/venv \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONIOENCODING=utf-8

# Tell the WebUI where to find the agent
ENV HERMES_WEBUI_AGENT_DIR=/opt/hermes-agent \
    HERMES_WEBUI_HOST=0.0.0.0 \
    HERMES_WEBUI_PORT=8787 \
    HERMES_WEBUI_STATE_DIR=/home/hermes/.hermes/webui \
    HERMES_WEBUI_DEFAULT_WORKSPACE=/workspace \
    HERMES_HOME=/home/hermes/.hermes

# Create non-root user
RUN useradd --create-home --shell /bin/bash hermes \
    && mkdir -p /workspace \
    && chown -R hermes:hermes /app /opt/venv /opt/hermes-agent /workspace /home/hermes

USER hermes

EXPOSE 8787

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

# Run the WebUI server (which runs Hermes Agent in-process)
CMD ["python", "/app/server.py"]
