#!/bin/bash

# MusicBrainz Cleaner - Quick Start Script
# This script automates the startup of MusicBrainz services

set -e

echo "🚀 Starting MusicBrainz services..."

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    print_error "Docker is not running. Please start Docker Desktop first."
    exit 1
fi

print_success "Docker is running"

# Check if we're in the right directory
if [ ! -f "docker-compose.yml" ]; then
    print_error "This script must be run from the musicbrainz-cleaner directory"
    exit 1
fi

# Check if musicbrainz-docker directory exists
if [ ! -d "../musicbrainz-docker" ]; then
    print_error "musicbrainz-docker directory not found. Please ensure you're in the musicbrainz-server directory."
    exit 1
fi

# Navigate to musicbrainz-docker
cd ../musicbrainz-docker

print_status "Checking for port conflicts..."

# Check if port 5000 is available
if lsof -i :5000 > /dev/null 2>&1; then
    print_warning "Port 5000 is in use. Using port 5001 instead."
    PORT=5001
else
    print_success "Port 5000 is available"
    PORT=5000
fi

# Stop any existing containers
print_status "Stopping existing containers..."
docker-compose down > /dev/null 2>&1 || true

# Remove any conflicting containers
print_status "Cleaning up conflicting containers..."
docker rm -f musicbrainz-docker-db-1 > /dev/null 2>&1 || true

# Start services
print_status "Starting MusicBrainz services on port $PORT..."
MUSICBRAINZ_WEB_SERVER_PORT=$PORT docker-compose up -d

print_success "Services started successfully!"

# Wait for database to be ready
print_status "Waiting for database to initialize (this may take 5-10 minutes)..."
print_status "You can monitor progress with: docker-compose logs -f db"

# Check if database is ready
attempts=0
max_attempts=60
while [ $attempts -lt $max_attempts ]; do
    if docker-compose exec -T db pg_isready -U musicbrainz > /dev/null 2>&1; then
        print_success "Database is ready!"
        break
    fi
    attempts=$((attempts + 1))
    print_status "Waiting for database... (attempt $attempts/$max_attempts)"
    sleep 10
done

if [ $attempts -eq $max_attempts ]; then
    print_warning "Database may still be initializing. You can check status with: docker-compose logs db"
fi

# Create .env file in musicbrainz-cleaner directory
cd ../musicbrainz-cleaner

print_status "Creating environment configuration..."

cat > .env << EOF
# Database connection (default Docker setup)
DB_HOST=172.18.0.2
DB_PORT=5432
DB_NAME=musicbrainz_db
DB_USER=musicbrainz
DB_PASSWORD=musicbrainz

# MusicBrainz web server
MUSICBRAINZ_WEB_SERVER_PORT=$PORT
EOF

print_success "Environment configuration created"

# Test connection
print_status "Testing connection..."
if docker-compose run --rm musicbrainz-cleaner python3 -c "
import sys
sys.path.insert(0, '/app')
from src.api.database import MusicBrainzDatabase
try:
    db = MusicBrainzDatabase()
    print('✅ Database connection successful')
except Exception as e:
    print(f'❌ Database connection failed: {e}')
    sys.exit(1)
" 2>/dev/null; then
    print_success "Connection test passed!"
else
    print_warning "Connection test failed. Services may still be initializing."
fi

echo ""
print_success "MusicBrainz services are now running!"
echo ""
echo "📊 Service Status:"
echo "  - Web Server: http://localhost:$PORT"
echo "  - Database: PostgreSQL (internal)"
echo "  - Search: Solr (internal)"
echo ""
echo "🧪 Next steps:"
echo "  1. Run quick test: python3 quick_test_20.py"
echo "  2. Run larger test: python3 bulk_test_1000.py"
echo "  3. Use cleaner: python3 -m src.cli.main --input your_file.json --output cleaned.json"
echo ""
echo "📋 Useful commands:"
echo "  - View logs: cd ../musicbrainz-docker && docker-compose logs -f"
echo "  - Stop services: cd ../musicbrainz-docker && docker-compose down"
echo "  - Check status: cd ../musicbrainz-docker && docker-compose ps"
echo "" 