#!/bin/bash
# Automation System Deployment Script
# Run this script to complete the automation system deployment

set -e  # Exit on error

echo "========================================="
echo "IGNY8 Automation System Deployment"
echo "========================================="
echo ""

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

# Check if running from correct directory
if [ ! -f "manage.py" ]; then
    echo -e "${RED}Error: Please run this script from the backend directory${NC}"
    echo "cd /data/app/igny8/backend && ./deploy_automation.sh"
    exit 1
fi

echo -e "${YELLOW}Step 1: Creating log directory...${NC}"
mkdir -p logs/automation
chmod 755 logs/automation
echo -e "${GREEN}✓ Log directory created${NC}"
echo ""

echo -e "${YELLOW}Step 2: Running database migrations...${NC}"
python3 manage.py makemigrations
python3 manage.py migrate
echo -e "${GREEN}✓ Migrations complete${NC}"
echo ""

echo -e "${YELLOW}Step 3: Checking Celery services...${NC}"
if docker ps | grep -q celery; then
    echo -e "${GREEN}✓ Celery worker is running${NC}"
else
    echo -e "${RED}⚠ Celery worker is NOT running${NC}"
    echo "Start with: docker-compose up -d celery"
fi

if docker ps | grep -q beat; then
    echo -e "${GREEN}✓ Celery beat is running${NC}"
else
    echo -e "${RED}⚠ Celery beat is NOT running${NC}"
    echo "Start with: docker-compose up -d celery-beat"
fi
echo ""

echo -e "${YELLOW}Step 4: Verifying cache backend...${NC}"
python3 -c "
from django.core.cache import cache
try:
    cache.set('test_key', 'test_value', 10)
    if cache.get('test_key') == 'test_value':
        print('${GREEN}✓ Cache backend working${NC}')
    else:
        print('${RED}⚠ Cache backend not working properly${NC}')
except Exception as e:
    print('${RED}⚠ Cache backend error:', str(e), '${NC}')
" || echo -e "${RED}⚠ Could not verify cache backend${NC}"
echo ""

echo -e "${YELLOW}Step 5: Testing automation API...${NC}"
python3 manage.py shell << EOF
from igny8_core.business.automation.services import AutomationService
from igny8_core.modules.system.models import Account, Site

try:
    account = Account.objects.first()
    site = Site.objects.first()
    if account and site:
        service = AutomationService(account, site)
        estimate = service.estimate_credits()
        print('${GREEN}✓ AutomationService working - Estimated credits:', estimate, '${NC}')
    else:
        print('${YELLOW}⚠ No account or site found - create one first${NC}')
except Exception as e:
    print('${RED}⚠ AutomationService error:', str(e), '${NC}')
EOF
echo ""

echo -e "${YELLOW}Step 6: Checking Celery beat schedule...${NC}"
if docker ps | grep -q celery; then
    CELERY_CONTAINER=$(docker ps | grep celery | grep -v beat | awk '{print $1}')
    docker exec $CELERY_CONTAINER celery -A igny8_core inspect scheduled 2>/dev/null | grep -q "check-scheduled-automations" && \
        echo -e "${GREEN}✓ Automation task scheduled in Celery beat${NC}" || \
        echo -e "${YELLOW}⚠ Automation task not found in schedule (may need restart)${NC}"
else
    echo -e "${YELLOW}⚠ Celery worker not running - cannot check schedule${NC}"
fi
echo ""

echo "========================================="
echo -e "${GREEN}Deployment Steps Completed!${NC}"
echo "========================================="
echo ""

echo "Next steps:"
echo "1. Restart Celery services to pick up new tasks:"
echo "   docker-compose restart celery celery-beat"
echo ""
echo "2. Access the frontend at /automation page"
echo ""
echo "3. Test the automation:"
echo "   - Click [Configure] to set up schedule"
echo "   - Click [Run Now] to start automation"
echo "   - Monitor progress in real-time"
echo ""
echo "4. Check logs:"
echo "   tail -f logs/automation/{account_id}/{site_id}/{run_id}/automation_run.log"
echo ""
echo -e "${YELLOW}For troubleshooting, see: AUTOMATION-DEPLOYMENT-CHECKLIST.md${NC}"
