#!/bin/bash

# StoryCove Deployment Script
# This script handles deployment with automatic Solr volume cleanup

set -e

echo "🚀 Starting StoryCove deployment..."

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

# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}❌ docker-compose not found. Please install docker-compose first.${NC}"
    exit 1
fi

# Stop existing containers
echo -e "${YELLOW}📦 Stopping existing containers...${NC}"
docker-compose down

# Remove Solr volume to force recreation with fresh cores
echo -e "${YELLOW}🗑️  Removing Solr data volume...${NC}"
docker volume rm storycove_solr_data 2>/dev/null || echo "Solr volume doesn't exist yet (first run)"

# Build and start containers
echo -e "${YELLOW}🏗️  Building and starting containers...${NC}"
docker-compose up -d --build

# Wait for services to be healthy
echo -e "${YELLOW}⏳ Waiting for services to be healthy...${NC}"
sleep 5

# Check if backend is ready
echo -e "${YELLOW}🔍 Checking backend health...${NC}"
MAX_RETRIES=30
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if docker-compose exec -T backend curl -f http://localhost:8080/api/health &>/dev/null; then
        echo -e "${GREEN}✅ Backend is healthy${NC}"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT+1))
    echo "Waiting for backend... ($RETRY_COUNT/$MAX_RETRIES)"
    sleep 2
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    echo -e "${RED}❌ Backend failed to start${NC}"
    docker-compose logs backend
    exit 1
fi

# Apply database migrations
echo -e "${YELLOW}🗄️  Applying database migrations...${NC}"
docker-compose run --rm migrations
echo -e "${GREEN}✅ Database migrations applied${NC}"

# Check if Solr is ready
echo -e "${YELLOW}🔍 Checking Solr health...${NC}"
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if docker-compose exec -T backend curl -f http://solr:8983/solr/admin/ping &>/dev/null; then
        echo -e "${GREEN}✅ Solr is healthy${NC}"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT+1))
    echo "Waiting for Solr... ($RETRY_COUNT/$MAX_RETRIES)"
    sleep 2
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    echo -e "${RED}❌ Solr failed to start${NC}"
    docker-compose logs solr
    exit 1
fi

echo -e "${GREEN}✅ Deployment complete!${NC}"
echo ""
echo "📊 Service status:"
docker-compose ps
echo ""
echo "🌐 Application is available at http://localhost:6925"
echo "🔧 Solr Admin UI is available at http://localhost:8983"
echo ""
echo "📝 Note: The application will automatically perform bulk reindexing on startup."
echo "   Check backend logs with: docker-compose logs -f backend"
