#!/bin/bash
# Migration script to replace packages/wallet_utils with django-wallet-utils

set -e  # Exit on error

echo "🚀 Starting migration to standalone django-wallet-utils..."

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if we're in the right directory
if [ ! -f "backend/manage.py" ]; then
    echo -e "${RED}❌ Error: Please run this script from the telegram-earn project root${NC}"
    exit 1
fi

# Check if django-wallet-utils exists
WALLET_UTILS_PATH="/home/cursorai/projects/django-wallet-utils"
if [ ! -d "$WALLET_UTILS_PATH" ]; then
    echo -e "${RED}❌ Error: django-wallet-utils not found at $WALLET_UTILS_PATH${NC}"
    echo "Please ensure the standalone package exists before running this script."
    exit 1
fi

echo -e "${YELLOW}📦 Step 1: Installing django-wallet-utils...${NC}"
cd backend
pip install -e "$WALLET_UTILS_PATH"
echo -e "${GREEN}✅ Package installed${NC}"

echo -e "${YELLOW}📝 Step 2: Checking requirements.txt...${NC}"
if ! grep -q "django-wallet-utils\|wallet-utils" requirements.txt; then
    echo "" >> requirements.txt
    echo "#### Wallet utilities" >> requirements.txt
    echo "# For development (editable install from local path)" >> requirements.txt
    echo "-e $WALLET_UTILS_PATH" >> requirements.txt
    echo -e "${GREEN}✅ Added to requirements.txt${NC}"
else
    echo -e "${YELLOW}⚠️  Package already in requirements.txt, skipping...${NC}"
fi

echo -e "${YELLOW}⚙️  Step 3: Checking INSTALLED_APPS...${NC}"
if ! grep -q '"wallet_utils"' config/settings_base.py; then
    echo -e "${YELLOW}⚠️  wallet_utils not found in INSTALLED_APPS${NC}"
    echo "Please add 'wallet_utils' to INSTALLED_APPS in config/settings_base.py"
    echo "See docs/migrate-to-standalone-wallet-utils.md for details"
else
    echo -e "${GREEN}✅ wallet_utils found in INSTALLED_APPS${NC}"
fi

echo -e "${YELLOW}🗄️  Step 4: Running migrations...${NC}"
python manage.py migrate wallet_utils
echo -e "${GREEN}✅ Migrations completed${NC}"

echo -e "${YELLOW}🧪 Step 5: Testing imports...${NC}"
python manage.py shell << EOF
from wallet_utils import WalletService, WalletRepository
from wallet_utils.models import WalletTransaction
print("✅ All imports successful!")
exit()
EOF

echo -e "${GREEN}✅ Import test passed${NC}"

echo ""
echo -e "${GREEN}✅ Migration completed successfully!${NC}"
echo ""
echo -e "${YELLOW}📋 Next steps:${NC}"
echo "1. Test your application thoroughly"
echo "2. Once confirmed working, remove old package: rm -rf packages/wallet_utils"
echo "3. Commit changes to git"
echo ""
echo -e "${YELLOW}📖 For more details, see: docs/migrate-to-standalone-wallet-utils.md${NC}"
