FROM ubuntu:24.04 AS base

ENV DEBIAN_FRONTEND=noninteractive
ENV NODE_VERSION=22

# Base deps
RUN apt-get update && apt-get install -y \
    curl git build-essential pkg-config libssl-dev \
    python3 python3-pip python3-venv \
    && rm -rf /var/lib/apt/lists/*

# Node.js
RUN curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash - \
    && apt-get install -y nodejs \
    && npm install -g npm@latest

# Rust (for RTK)
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"

# ========== RTK ==========
FROM base AS rtk-builder
WORKDIR /build
RUN git clone https://github.com/rtk-ai/rtk.git && cd rtk && cargo build --release
RUN cp /build/rtk/target/release/rtk /usr/local/bin/rtk

# ========== ComfyUI ==========
FROM base AS comfyui
WORKDIR /app/comfy
RUN git clone https://github.com/comfyanonymous/ComfyUI.git .
RUN python3 -m venv venv \
    && . venv/bin/activate \
    && pip install --upgrade pip \
    && pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu \
    && pip install -r requirements.txt \
    && pip install comfy-cli
ENV PATH="/app/comfy/venv/bin:${PATH}"

# ========== Metapi ==========
FROM base AS metapi
WORKDIR /app/metapi
COPY . .
RUN npm install
RUN npm run build --if-present

# ========== Final ==========
FROM ubuntu:24.04
ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get install -y \
    curl python3 python3-pip python3-venv nodejs \
    ca-certificates supervisor \
    && rm -rf /var/lib/apt/lists/*

# Copy components
COPY --from=rtk-builder /usr/local/bin/rtk /usr/local/bin/rtk
COPY --from=comfyui /app/comfy /app/comfy
COPY --from=comfyui /app/comfy/venv /app/comfy/venv
COPY --from=metapi /app/metapi /app/metapi
COPY --from=metapi /usr/lib/node_modules /usr/lib/node_modules

# Node path
ENV PATH="/app/comfy/venv/bin:/usr/local/bin:${PATH}"
ENV COMFYUI_BASE=http://127.0.0.1:8188
ENV AUTH_TOKEN=change-me-admin-token

WORKDIR /app/metapi

# Supervisor config
RUN mkdir -p /var/log/supervisor
COPY <<'EOF' /etc/supervisor/conf.d/all.conf
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisor/supervisord.log
pidfile=/tmp/supervisord.pid

[program:metapi-server]
command=npm run dev:server
directory=/app/metapi
autorestart=true
stdout_logfile=/var/log/supervisor/metapi-server.log
stderr_logfile=/var/log/supervisor/metapi-server.err

[program:metapi-web]
command=npx vite --host 0.0.0.0 --port 5173
directory=/app/metapi
autorestart=true
stdout_logfile=/var/log/supervisor/metapi-web.log
stderr_logfile=/var/log/supervisor/metapi-web.err

[program:comfyui]
command=python3 main.py --listen 0.0.0.0 --port 8188
directory=/app/comfy
autorestart=true
stdout_logfile=/var/log/supervisor/comfyui.log
stderr_logfile=/var/log/supervisor/comfyui.err
EOF

EXPOSE 4000 5173 8188

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