# Use Ubuntu 24.04 as base (supports deadsnakes PPA for Python 3.11)
# This matches voice-agent's Python 3.11 environment
FROM ubuntu:24.04

# Set working directory
WORKDIR /app

# Install Node.js 20.x (required for Motia)
RUN apt-get update && \
    apt-get install -y curl ca-certificates gnupg && \
    mkdir -p /etc/apt/keyrings && \
    curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
    echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \
    apt-get update && \
    apt-get install -y nodejs && \
    rm -rf /var/lib/apt/lists/*

# Move application files (Motia projects don't need separate dependency installation)
COPY . .

# Pre-install motia CLI to avoid downloading on every start
RUN npm install -g motia@latest

# Create a dummy tsconfig.base.json if it doesn't exist (monorepo compatibility)
RUN echo '{"compilerOptions": {"target": "ES2020", "module": "commonjs"}}' > /tsconfig.base.json

# Install Node.js dependencies (required by various steps)
RUN npm install uuid@10.0.0 @supabase/supabase-js@2.75.0 livekit-server-sdk@2.14.0

# Setup python steps dependencies (for Motia)
RUN npx motia@latest install

# Install Python 3.11 using deadsnakes PPA (matches voice-agent configuration)
# Python 3.11 is proven to work on Railway (voice-agent uses python311 via Nixpacks)
# Python 3.13 has asyncio initialization deadlock in Railway's container environment
RUN apt-get update && \
    apt-get install -y software-properties-common && \
    add-apt-repository ppa:deadsnakes/ppa && \
    apt-get update && \
    apt-get install -y python3.11 python3.11-venv python3.11-dev pip && \
    rm -rf /var/lib/apt/lists/*

# Create unified Python venv for all bots using Python 3.11
# IMPORTANT: Use Python 3.11 (not 3.13) - proven compatible with Railway environment
RUN pip install --no-cache-dir --break-system-packages uv && \
    python3.11 -m venv /app/.venv

# Install all bot dependencies in unified venv
# Tool forwarder dependencies
RUN uv pip install --python /app/.venv/bin/python \
    -r bots/tool-forwarder/requirements.txt

# Screenshare bot dependencies (from pyproject.toml)
RUN uv pip install --python /app/.venv/bin/python \
    bots/screenshare-bot/.

# Install Playwright browsers (Chromium for screenshot capture)
# --with-deps installs all system dependencies (libnss3, libglib2.0-0, etc.)
RUN /app/.venv/bin/playwright install --with-deps chromium

# Expose outside access to the motia project
EXPOSE 3000

# Run your application in production mode (serves API endpoints only, no workbench)
# Railway will inject PORT env var, but we default to 3000
CMD sh -c "npx motia start --port ${PORT:-3000} --host 0.0.0.0"
