#!/bin/bash
set -e

PORT="${DOBBY_PORT:-8420}"
CONFIG="/data/dobby.yaml"
LOG_DIR="/data/logs"
mkdir -p "$LOG_DIR"

echo "=== Dobby Multi-Tenant Container ==="
echo "Port: $PORT"
echo "Config: $CONFIG"

# Generate config if it doesn't exist
if [ ! -f "$CONFIG" ]; then
    cat > "$CONFIG" <<YAML
host: "0.0.0.0"
port: ${PORT}
db_path: "/data/dobby.db"
results_dir: "/data/results"
hub_url: "${DOBBY_HUB_URL:-}"
max_concurrent_agents: 3
default_timeout: 3600
stale_timeout: 1800
YAML
    echo "Generated config at $CONFIG"
fi

# Start Dobby daemon in background
echo "Starting Dobby daemon on port $PORT..."
dobby start --config "$CONFIG" > "$LOG_DIR/daemon.log" 2>&1 &
DAEMON_PID=$!

# Wait for daemon to be healthy
echo "Waiting for daemon health check..."
for i in $(seq 1 30); do
    if curl -sf "http://localhost:${PORT}/health" > /dev/null 2>&1; then
        echo "Daemon is healthy!"
        break
    fi
    if ! kill -0 "$DAEMON_PID" 2>/dev/null; then
        echo "ERROR: Daemon process died. Logs:"
        cat "$LOG_DIR/daemon.log"
        exit 1
    fi
    sleep 2
done

# Check if health check succeeded
if ! curl -sf "http://localhost:${PORT}/health" > /dev/null 2>&1; then
    echo "ERROR: Daemon failed to become healthy after 60s. Logs:"
    tail -50 "$LOG_DIR/daemon.log"
    exit 1
fi

# Start Slack bot if tokens are provided
if [ -n "$SLACK_BOT_TOKEN" ] && [ -n "$SLACK_APP_TOKEN" ]; then
    echo "Starting Slack bot..."
    dobby slack --dobby-url "http://127.0.0.1:${PORT}" > "$LOG_DIR/slack.log" 2>&1 &
    SLACK_PID=$!
    echo "Slack bot started (PID: $SLACK_PID)"
else
    echo "Slack tokens not set, skipping Slack bot"
fi

echo "=== Container ready ==="
echo "Dashboard: http://localhost:${PORT}/dashboard"
echo "To authenticate Claude Code, exec into this container:"
echo "  docker exec -it <container> claude"

# Keep container alive by waiting on daemon
wait "$DAEMON_PID"
