#!/bin/bash

# --- Deployment Script for AI Hub (Server Side) ---
# This script is designed to automate the deployment of the AI Hub application
# using Docker Compose. It's intended to be run on the production server.

# Set the project directory to the directory where this script is located.
# We expect this script to be in 'scripts/' or root.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")" # Assuming it's in scripts/
if [ ! -f "$PROJECT_DIR/docker-compose.yml" ]; then
    PROJECT_DIR="$SCRIPT_DIR" # Fallback if run from root
fi

cd "$PROJECT_DIR" || { echo "Error: Project directory '$PROJECT_DIR' not found. Exiting."; exit 1; }

# Find the correct docker-compose command
if docker compose version &> /dev/null; then
    DOCKER_CMD="docker compose"
else
    DOCKER_CMD="docker-compose"
fi

echo "🚀 Starting AI Hub deployment process..."

BUILD_BINARIES=true
FAST_DEPLOY=false
for arg in "$@"; do
    if [ "$arg" == "--skip-binaries" ]; then
        BUILD_BINARIES=false
    fi
    if [ "$arg" == "--fast" ]; then
        FAST_DEPLOY=true
        BUILD_BINARIES=false
    fi
done

# 1. Base compose file
COMPOSE_FILES="-f $PROJECT_DIR/docker-compose.yml"

# 2. Check for production overrides (Jerxie specific)
if [ -f "$PROJECT_DIR/deployment/jerxie-prod/docker-compose.production.yml" ]; then
    echo "🏗️ Applying Jerxie Production overrides..."
    COMPOSE_FILES="$COMPOSE_FILES -f $PROJECT_DIR/deployment/jerxie-prod/docker-compose.production.yml"
fi


# 3. Check for test nodes
if [ -f "$PROJECT_DIR/deployment/test-nodes/docker-compose.test-nodes.yml" ]; then
    echo "🔗 Including Internal Test Nodes in deployment..."
    COMPOSE_FILES="$COMPOSE_FILES -f $PROJECT_DIR/deployment/test-nodes/docker-compose.test-nodes.yml"
fi

if [ "$FAST_DEPLOY" = true ]; then
    echo "⚡ Fast Deployment: Skipping 'down' and '--build', but forcing container recreation to reload code..."
    sudo $DOCKER_CMD $COMPOSE_FILES up -d --force-recreate > /tmp/deploy_log.txt 2>&1
else
    echo "🛑 Stopping and removing old Docker containers and networks..."
    sudo $DOCKER_CMD $COMPOSE_FILES down --remove-orphans || true
    echo "🏗️ Building and starting new containers..."
    sudo $DOCKER_CMD $COMPOSE_FILES up -d --build > /tmp/deploy_log.txt 2>&1
fi

echo "✅ Containers started! Checking status..."
cat /tmp/deploy_log.txt
sudo docker ps --filter "name=ai_"
sudo docker ps --filter "name=cortex-"

echo "✅ Deployment complete! The AI Hub application is now running."

echo "🧹 Cleaning up unused Docker resources..."
sudo docker image prune -f || true

echo "🏗️ Building standalone Agent Node binaries..."
if [ "$BUILD_BINARIES" = true ]; then
    if [ -f "agent-node/scripts/build_binaries.sh" ]; then
        bash agent-node/scripts/build_binaries.sh
    else
        echo "⚠️ agent-node/scripts/build_binaries.sh not found, skipping binary build."
    fi
else
    echo "⏭️ Skipping binary build."
fi

echo "✨ Cleanup finished."
