#!/bin/bash
set -e

echo "=== Deploy: max_bot ==="
cd /opt/projects/aegisone-py/max_bot

# Stop container first
echo "--- Stopping max_bot ---"
docker stop max_bot 2>/dev/null || true
docker rm max_bot 2>/dev/null || true

# Recreate container from existing image but don't start
echo "--- Creating temp container for cleanup ---"
docker create --name max_bot_tmp max_bot-max_bot:latest 2>/dev/null || {
    echo "Image not available, pulling/building..."
    # We need to build the Docker image, let's fix the DNS issue differently
    # Copy requirements.txt and install deps on host, then build
    
    # Alternative: use python:3.12-slim but install DNS config
    cat > Dockerfile.build << 'DOCKER'
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN mkdir -p /etc/docker && echo "nameserver 8.8.8.8" > /etc/resolv.conf || true
RUN pip install --no-cache-dir -r requirements.txt --extra-index-url https://pypi.org/simple/ || \
    pip install --no-cache-dir -r requirements.txt --index-url https://pypi.org/simple/
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8002"]
DOCKER
    
    docker build -f Dockerfile.build --network host -t max_bot-max_bot:latest . 2>&1 | tail -5 || {
        echo "Build failed, trying without network host..."
        docker build -f Dockerfile.build --network bridge -t max_bot-max_bot:latest . 2>&1 | tail -5 || {
            echo "Build failed again, will use docker cp approach"
        }
    }
}

echo "--- Creating max_bot from image ---"
# Remove temp container if exists
docker rm max_bot_tmp 2>/dev/null || true

# Create new container
docker create --name max_bot --network host \
    -e BOT_DATABASE_URL="postgresql+asyncpg://aegisone:aegisone_pass@localhost:5432/aegisone" \
    -e BOT_MAX_TOKEN="f9LHodD0cOKkk03DYXj906MdIeRs3HdDo0BC5H2fLMVCMz3PA_Vx4aJqt2l2qPLM5zd5EQ1Zh6APxzpw2UYE" \
    -e BOT_WEBHOOK_URL="https://max.aegisone.ru/webhook" \
    -e BOT_WEBHOOK_SECRET="aegisone_bot_secret_2026" \
    -e BOT_CONFIG_PHP_PATH="/var/www/html/config.php" \
    -e BOT_PHP_SENDMAIL_PATH="/usr/sbin/sendmail" \
    --restart always \
    max_bot-max_bot:latest 2>&1 || echo "Image build failed, using alternative..."

# Check if image exists
if docker image inspect max_bot-max_bot:latest >/dev/null 2>&1; then
    echo "Image exists, proceeding..."
    docker start max_bot
    sleep 3
    echo "--- Health check ---"
    curl -s -o /dev/null -w "max.aegisone.ru: %{http_code}\n" https://max.aegisone.ru/health
    echo "--- Logs ---"
    docker logs --tail 20 max_bot 2>&1
else
    echo "Image not available, using manual copy approach..."
    # Use the container that was already created (might not exist)
    docker start max_bot 2>/dev/null || true
fi

echo "=== DEPLOY STEP 1 FINISHED ==="
