# ============================================================
# IT0 OpenClaw Bridge Image
# Based on the official openclaw/openclaw source.
# Adds an IT0 Bridge process (Node.js, port 3000) that connects
# to the OpenClaw gateway (ws://127.0.0.1:18789) and exposes
# a REST management API for IT0 agent-service.
#
# Two processes managed by supervisord:
#   1. openclaw  — the original OpenClaw gateway + CLI
#   2. it0-bridge — this package's compiled Node.js server
# ============================================================

# ── Stage 1: Build OpenClaw from source ──────────────────────
FROM node:20-slim AS openclaw-builder

RUN npm install -g pnpm@latest

WORKDIR /build/openclaw
# Clone the latest openclaw source
RUN apt-get update && apt-get install -y git && \
    git clone --depth 1 https://github.com/openclaw/openclaw.git . && \
    pnpm install --frozen-lockfile && \
    pnpm run build

# ── Stage 2: Build IT0 Bridge ─────────────────────────────────
FROM node:20-slim AS bridge-builder

WORKDIR /build/bridge
COPY package.json tsconfig.json ./
RUN npm install
COPY src/ ./src/
RUN npm run build

# ── Stage 3: Final image ──────────────────────────────────────
FROM node:20-slim

RUN apt-get update && apt-get install -y \
    supervisor \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user (matching openclaw's expected uid)
RUN useradd -m -u 1000 node 2>/dev/null || true

# ── OpenClaw files ────────────────────────────────────────────
WORKDIR /app/openclaw
COPY --from=openclaw-builder --chown=node:node /build/openclaw/dist ./dist
COPY --from=openclaw-builder --chown=node:node /build/openclaw/node_modules ./node_modules
COPY --from=openclaw-builder --chown=node:node /build/openclaw/package.json ./

# ── IT0 Bridge files ──────────────────────────────────────────
WORKDIR /app/bridge
COPY --from=bridge-builder --chown=node:node /build/bridge/dist ./dist
COPY --from=bridge-builder --chown=node:node /build/bridge/node_modules ./node_modules
COPY --from=bridge-builder --chown=node:node /build/bridge/package.json ./

# ── supervisord config ────────────────────────────────────────
COPY supervisord.conf /etc/supervisor/conf.d/openclaw-bridge.conf

# ── Data directory for openclaw config + workspace ───────────
RUN mkdir -p /home/node/.openclaw/workspace && \
    chown -R node:node /home/node/.openclaw

# Expose only the IT0 Bridge port (OpenClaw gateway 18789 is internal only)
EXPOSE 3000

USER node

CMD ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisor/conf.d/openclaw-bridge.conf"]
