#!/bin/bash
# MCP-ZERO Integration Script
# Links this burn folder with the main MCP-ZERO project

set -e

# Color definitions
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get the absolute path of this burn folder
BURN_FOLDER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ -z "$1" ]; then
  echo -e "${RED}Error: Please provide the path to MCP-ZERO main project${NC}"
  echo "Usage: $0 /path/to/mcp_zero"
  exit 1
fi

# Get the absolute path of MCP-ZERO main project
MCP_PROJECT="$(cd "$1" 2>/dev/null && pwd || echo "")"

if [ -z "${MCP_PROJECT}" ] || [ ! -d "${MCP_PROJECT}" ]; then
  echo -e "${RED}Error: Invalid MCP-ZERO project path${NC}"
  exit 1
fi

# Check if it's a valid MCP-ZERO project
if [ ! -f "${MCP_PROJECT}/burn.sh" ]; then
  echo -e "${RED}Error: Not a valid MCP-ZERO project${NC}"
  exit 1
fi

echo -e "${BLUE}Integrating burn folder with MCP-ZERO project...${NC}"

# Create symbolic links for shared resources
ln -sf "${MCP_PROJECT}/src" "${BURN_FOLDER}/src"

# Copy agent models if they exist
if [ -d "${MCP_PROJECT}/agents/models" ]; then
  echo -e "${BLUE}Copying agent models...${NC}"
  rsync -av "${MCP_PROJECT}/agents/models/" "${BURN_FOLDER}/agents/models/"
fi

# Set up ZETA components if they exist
if [ -d "${MCP_PROJECT}/src/zeta_llm" ] || [ -d "${MCP_PROJECT}/src/zeta_cuda" ]; then
  echo -e "${BLUE}Setting up ZETA components...${NC}"
  
  # Create paths configuration
  cat > "${BURN_FOLDER}/.mcp/config/paths.json" << PATHSEOF
{
  "mcp_project_path": "${MCP_PROJECT}",
  "zeta_components": {
    "llm_path": "${MCP_PROJECT}/src/zeta_llm",
    "cuda_path": "${MCP_PROJECT}/src/zeta_cuda",
    "tensor_path": "${MCP_PROJECT}/src/zeta_tensor",
    "face_path": "${MCP_PROJECT}/src/zeta_face"
  }
}
PATHSEOF

  # Update docker-compose to use the right paths
  if [ -f "${BURN_FOLDER}/docker/docker-compose.llm.yaml" ]; then
    sed -i "s|context: .|context: ${MCP_PROJECT}|g" "${BURN_FOLDER}/docker/docker-compose.llm.yaml"
  fi
  
  echo -e "${GREEN}ZETA components configured${NC}"
fi

# Update configuration to point to the right paths
echo '{"mcp_project_path": "'"${MCP_PROJECT}"'"}' > "${BURN_FOLDER}/.mcp/config/paths.json"

# Update docker networks to ensure MCP services can communicate
if [ -f "${BURN_FOLDER}/docker/docker-compose.yaml" ]; then
  echo -e "${BLUE}Updating Docker network configuration...${NC}"
  
  # Create the MCP network if it doesn't exist
  docker network create mcp-network 2>/dev/null || true
  
  # Update the docker-compose files to use the network
  sed -i 's/external: false/external: true/g' "${BURN_FOLDER}/docker/docker-compose.yaml" 2>/dev/null || true
fi

# Create a convenience script for starting all services
cat > "${BURN_FOLDER}/start_all.sh" << STARTEOF
#!/bin/bash
# Start all MCP-ZERO services including containers

BURN_FOLDER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${BURN_FOLDER}"

# Start core services
./mcp-cli.sh start all

# Check if we have LLM services
if [ -f "${BURN_FOLDER}/scripts/start_llm_services.sh" ]; then
  ./scripts/start_llm_services.sh
fi

# Check if we have docker-compose.yaml
if [ -f "${BURN_FOLDER}/docker/docker-compose.yaml" ]; then
  cd "${BURN_FOLDER}"
  docker-compose -f docker/docker-compose.yaml up -d
fi

echo -e "All MCP-ZERO services started!"
STARTEOF

chmod +x "${BURN_FOLDER}/start_all.sh"

# Setup offline-first resilience enforcement
echo -e "${BLUE}Configuring offline-first resilience...${NC}"

# Create offline mode toggle script
cat > "${BURN_FOLDER}/toggle_offline.sh" << OFFLINEOF
#!/bin/bash
# Toggle offline mode for MCP-ZERO

BURN_FOLDER="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ "$1" == "enable" ]; then
  echo "Enabling offline mode"
  echo "Offline mode enabled on $(date -Iseconds)" > "${BURN_FOLDER}/.mcp/locks/offline.lock"
  chmod 444 "${BURN_FOLDER}/.mcp/locks/offline.lock"
  echo "Offline mode enabled. Services will use local processing only."
elif [ "$1" == "disable" ]; then
  if [ -f "${BURN_FOLDER}/.mcp/locks/offline.lock" ]; then
    if [ "$(stat -c %a "${BURN_FOLDER}/.mcp/locks/offline.lock")" == "444" ]; then
      echo "Warning: Offline lock is immutable. You must use sudo to remove it:"
      echo "sudo rm ${BURN_FOLDER}/.mcp/locks/offline.lock"
      exit 1
    else
      rm "${BURN_FOLDER}/.mcp/locks/offline.lock"
      echo "Offline mode disabled. Services will attempt online connections."
    fi
  else
    echo "Offline mode is not enabled."
  fi
else
  echo "Usage: $0 enable|disable"
  exit 1
fi
OFFLINEOF

chmod +x "${BURN_FOLDER}/toggle_offline.sh"

# Implement single connection attempt pattern in docker scripts
echo -e "${BLUE}Implementing single connection attempt pattern...${NC}"
if [ -d "${BURN_FOLDER}/docker" ]; then
  mkdir -p "${BURN_FOLDER}/docker/scripts"
  cat > "${BURN_FOLDER}/docker/scripts/single_connection_attempt.sh" << SINGLEOF
#!/bin/bash
# Implement single connection attempt pattern for MCP-ZERO services

# Usage: ./single_connection_attempt.sh HOST PORT TIMEOUT
# Returns 0 if connection successful, 1 if failed

HOST="$1"
PORT="$2"
TIMEOUT="$3"

if [ -z "$HOST" ] || [ -z "$PORT" ]; then
  echo "Usage: $0 HOST PORT [TIMEOUT]"
  exit 1
fi

if [ -z "$TIMEOUT" ]; then
  TIMEOUT=5
fi

# Try a single connection
if timeout $TIMEOUT bash -c "cat < /dev/null > /dev/tcp/$HOST/$PORT" 2>/dev/null; then
  echo "Connection to $HOST:$PORT succeeded"
  exit 0
else
  echo "Connection to $HOST:$PORT failed, switching to offline mode"
  exit 1
fi
SINGLEOF

  chmod +x "${BURN_FOLDER}/docker/scripts/single_connection_attempt.sh"
fi

echo -e "${GREEN}Integration complete!${NC}"
echo -e "${YELLOW}You can now use this burn folder with the MCP-ZERO main project${NC}"
echo -e "${YELLOW}Run './start_all.sh' to start all services${NC}"
