#!/bin/bash

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

echo -e "${BLUE}🛑 Stopping Automated Development Pipeline${NC}"
echo "========================================"

# Check if we're in the right directory
if [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}❌ Error: docker-compose.yml not found. Please run from project root directory.${NC}"
    exit 1
fi

# Detect Docker Compose command
if command -v "docker" &> /dev/null && docker compose version &> /dev/null; then
    DOCKER_COMPOSE="docker compose"
elif command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE="docker-compose"
else
    echo -e "${RED}❌ Docker Compose is not available.${NC}"
    exit 1
fi

# Show current running services
echo -e "${BLUE}📊 Current running services:${NC}"
$DOCKER_COMPOSE ps

echo ""
echo -e "${BLUE}⏹️  Stopping all services gracefully...${NC}"

# Stop services
$DOCKER_COMPOSE stop

echo -e "${BLUE}🗑️  Removing containers...${NC}"
$DOCKER_COMPOSE down

# Optional: Remove volumes
read -p "Do you want to remove all data volumes? This will delete all databases and reset the system. (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}🗑️  Removing volumes and data...${NC}"
    $DOCKER_COMPOSE down -v
    echo -e "${YELLOW}⚠️  All data has been removed!${NC}"
fi

# Clean up
echo -e "${BLUE}�� Cleaning up orphaned containers and networks...${NC}"
$DOCKER_COMPOSE down --remove-orphans

echo ""
echo -e "${GREEN}✅ All services stopped successfully!${NC}"
echo ""
echo -e "${BLUE}📝 Available commands:${NC}"
echo "  🚀 Start again: ./scripts/setup/start.sh"
echo "  📊 Check status: ./scripts/setup/status.sh"
echo "  🧹 Full cleanup: docker system prune -a"
