refactor and added logic for AI