#!/bin/bash

# =============================================================================
# UJAMAA DAO - DOCKER STARTUP SCRIPT
# =============================================================================

set -e

echo "🐳 Starting UjamaaDAO with Docker..."

# 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 installed and running
check_docker() {
    print_status "Checking Docker installation..."
    
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed. Please install Docker first."
        echo "Visit: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker is not running. Please start Docker first."
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose is not installed. Please install Docker Compose first."
        exit 1
    fi
    
    print_success "Docker is installed and running"
}

# Check if ports are available
check_ports() {
    print_status "Checking port availability..."
    
    ports=(5432 6379 8545 3001 5173)
    for port in "${ports[@]}"; do
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
            print_warning "Port $port is already in use"
            read -p "Do you want to continue anyway? (y/N): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                print_error "Aborting due to port conflicts"
                exit 1
            fi
        fi
    done
    
    print_success "Port check completed"
}

# Create necessary directories
create_directories() {
    print_status "Creating necessary directories..."
    
    mkdir -p nginx/logs
    mkdir -p server/uploads
    mkdir -p blockchain/artifacts
    mkdir -p blockchain/cache
    
    print_success "Directories created"
}

# Build and start services
start_services() {
    print_status "Building and starting Docker services..."
    
    # Build images
    print_status "Building Docker images..."
    docker-compose build --parallel
    
    # Start services
    print_status "Starting services..."
    docker-compose up -d
    
    print_success "Services started"
}

# Wait for services to be healthy
wait_for_services() {
    print_status "Waiting for services to be ready..."
    
    services=("ujamaa-postgres" "ujamaa-redis" "ujamaa-blockchain" "ujamaa-api" "ujamaa-client")
    
    for service in "${services[@]}"; do
        print_status "Waiting for $service..."
        
        # Wait up to 120 seconds for service to be healthy
        timeout=120
        counter=0
        
        while [ $counter -lt $timeout ]; do
            if docker-compose ps | grep $service | grep -q "healthy\|Up"; then
                print_success "$service is ready"
                break
            fi
            
            sleep 2
            counter=$((counter + 2))
            
            if [ $counter -ge $timeout ]; then
                print_error "$service failed to start within $timeout seconds"
                print_status "Checking logs for $service..."
                docker-compose logs $service
                exit 1
            fi
        done
    done
    
    print_success "All services are ready"
}

# Setup database
setup_database() {
    print_status "Setting up database..."
    
    # Wait a bit more for PostgreSQL to be fully ready
    sleep 5
    
    # Run database migrations
    print_status "Running database migrations..."
    docker-compose exec api npx prisma db push
    
    # Seed database
    print_status "Seeding database..."
    docker-compose exec api npx prisma db seed
    
    print_success "Database setup completed"
}

# Deploy smart contracts
deploy_contracts() {
    print_status "Deploying smart contracts..."
    
    # Deploy contracts to local blockchain
    docker-compose exec blockchain npx hardhat run scripts/deploy.js --network localhost
    
    print_success "Smart contracts deployed"
}

# Show status and URLs
show_status() {
    echo ""
    echo "🎉 UjamaaDAO is now running!"
    echo ""
    echo "📊 Service Status:"
    docker-compose ps
    echo ""
    echo "🌐 Access URLs:"
    echo "   Frontend:     http://localhost:5173"
    echo "   Backend API:  http://localhost:3001"
    echo "   API Docs:     http://localhost:3001/api-docs"
    echo "   Blockchain:   http://localhost:8545"
    echo ""
    echo "🔑 Default Credentials:"
    echo "   Email:        <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>"
    echo "   Password:     admin123"
    echo ""
    echo "📋 Useful Commands:"
    echo "   View logs:    docker-compose logs -f"
    echo "   Stop all:     docker-compose down"
    echo "   Restart:      docker-compose restart"
    echo "   Clean up:     docker-compose down -v"
    echo ""
    echo "🎯 Next Steps:"
    echo "   1. Open http://localhost:5173 in your browser"
    echo "   2. Connect MetaMask to http://localhost:8545"
    echo "   3. Import test account with private key:"
    echo "      0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"
    echo ""
}

# Cleanup function
cleanup() {
    print_status "Cleaning up..."
    docker-compose down
    exit 1
}

# Trap cleanup on script exit
trap cleanup INT TERM

# Main execution
main() {
    echo "🚀 UjamaaDAO Docker Setup"
    echo "========================="
    echo ""
    
    check_docker
    check_ports
    create_directories
    start_services
    wait_for_services
    setup_database
    deploy_contracts
    show_status
    
    print_success "Setup completed successfully!"
    
    # Keep script running to show logs
    print_status "Showing live logs (Ctrl+C to stop)..."
    docker-compose logs -f
}

# Run main function
main "$@"