#!/bin/bash
# Setup script for integration testing database

set -e

echo "🔧 Setting up test database for StructuredStore integration tests..."

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

# Check if postgres_test container exists
if ! docker ps -a | grep -q postgres_test; then
    echo "📦 Creating postgres_test container..."
    docker run -d \
        --name postgres_test \
        -e POSTGRES_DB=dsol_test \
        -e POSTGRES_USER=dsol_user \
        -e POSTGRES_PASSWORD=dsol_password \
        -p 5433:5432 \
        postgres:18

    echo "⏳ Waiting for PostgreSQL to be ready..."
    sleep 5
else
    # Start the container if it's stopped
    if ! docker ps | grep -q postgres_test; then
        echo "▶️  Starting postgres_test container..."
        docker start postgres_test
        sleep 3
    else
        echo "✅ postgres_test container is already running"
    fi
fi

# Set environment variable
export TEST_DATABASE_URL="postgresql+asyncpg://dsol_user:dsol_password@localhost:5433/dsol_test"

echo "✅ Test database is ready!"
echo ""
echo "📝 To use in your terminal:"
echo "   export TEST_DATABASE_URL=\"postgresql+asyncpg://dsol_user:dsol_password@localhost:5433/dsol_test\""
echo ""
echo "🧪 Run integration tests:"
echo "   python -m pytest tests/knowledge/test_structured_store_integration.py -v"
echo ""
echo "🧹 Clean up when done:"
echo "   docker stop postgres_test"
echo "   docker rm postgres_test"
