#!/bin/bash
set -e

# Entrypoint script for chocolate tempering machine container

# Function to wait for service
wait_for_service() {
    local host=$1
    local port=$2
    local service_name=$3
    
    echo "Waiting for $service_name..."
    while ! nc -z $host $port; do
        sleep 1
    done
    echo "$service_name is ready!"
}

# Function to run database migrations
run_migrations() {
    echo "Running database migrations..."
    alembic upgrade head
    echo "Database migrations completed"
}

# Function to create initial data
create_initial_data() {
    echo "Creating initial data..."
    python -c "
import asyncio
from src.tempering_machine.shared.database import init_database, create_tables

async def setup():
    init_database()
    await create_tables()
    print('Database tables created')

asyncio.run(setup())
"
}

# Main execution
case "$1" in
    web)
        echo "Starting chocolate tempering machine web service..."
        
        # Wait for Redis if configured
        if [ ! -z "$TEMPERING_REDIS__HOST" ]; then
            wait_for_service ${TEMPERING_REDIS__HOST:-redis} ${TEMPERING_REDIS__PORT:-6379} "Redis"
        fi
        
        # Wait for PostgreSQL if configured
        if [[ "$TEMPERING_DATABASE_URL" == postgresql* ]]; then
            DB_HOST=$(echo $TEMPERING_DATABASE_URL | sed -n 's/.*@\([^:]*\).*/\1/p')
            DB_PORT=$(echo $TEMPERING_DATABASE_URL | sed -n 's/.*:\([0-9]*\).*/\1/p')
            wait_for_service ${DB_HOST:-postgres} ${DB_PORT:-5432} "PostgreSQL"
        fi
        
        # Run migrations
        run_migrations
        
        # Create initial data
        create_initial_data
        
        # Start web service
        echo "Starting FastAPI web service..."
        exec python -m uvicorn tempering_machine.services.web.main:app \
            --host ${TEMPERING_WEB__HOST:-0.0.0.0} \
            --port ${TEMPERING_WEB__PORT:-8000} \
            --workers ${TEMPERING_WEB__WORKERS:-1} \
            --access-log
        ;;
        
    worker)
        echo "Starting background worker..."
        
        # Wait for Redis
        wait_for_service ${TEMPERING_REDIS__HOST:-redis} ${TEMPERING_REDIS__PORT:-6379} "Redis"
        
        # Start Celery worker
        exec celery -A tempering_machine.services.worker worker \
            --loglevel=${TEMPERING_LOG_LEVEL:-info} \
            --concurrency=2
        ;;
        
    migrate)
        echo "Running database migrations only..."
        run_migrations
        ;;
        
    shell)
        echo "Starting Python shell..."
        exec python -c "
import asyncio
from src.tempering_machine.shared.database import init_database
from src.tempering_machine.shared.config import settings

print('Chocolate Tempering Machine - Python Shell')
print(f'Environment: {settings.environment}')
print(f'Database: {settings.database.url}')
print('')

init_database()
print('Database initialized. You can now import and use the application modules.')
print('')

# Import commonly used modules
from tempering_machine.shared.models import *
from tempering_machine.services.hardware.hardware_manager import hardware_manager
from tempering_machine.services.recipe.recipe_controller import recipe_controller
from tempering_machine.services.safety.safety_monitor import safety_monitor

import IPython
IPython.start_ipython(argv=[])
"
        ;;
        
    test)
        echo "Running tests..."
        exec python -m pytest tests/ -v
        ;;
        
    *)
        echo "Usage: $0 {web|worker|migrate|shell|test}"
        echo ""
        echo "Commands:"
        echo "  web     - Start FastAPI web service (default)"
        echo "  worker  - Start Celery background worker"
        echo "  migrate - Run database migrations only"
        echo "  shell   - Start interactive Python shell"
        echo "  test    - Run test suite"
        exit 1
        ;;
esac