#!/bin/bash
# Setup Local Development Environment for AS4 Settlement
# Sets up Docker Compose and local configuration

set -e

echo "========================================="
echo "AS4 Settlement Local Development Setup"
echo "========================================="
echo ""

cd "$(dirname "$0")/.."

# Step 1: Check Docker
echo "Step 1: Checking Docker..."
if command -v docker &> /dev/null; then
    DOCKER_VERSION=$(docker --version)
    echo "   ✓ Docker installed: $DOCKER_VERSION"
else
    echo "   ✗ Docker not found. Please install Docker first."
    exit 1
fi

if command -v docker-compose &> /dev/null || docker compose version &> /dev/null; then
    echo "   ✓ Docker Compose available"
else
    echo "   ✗ Docker Compose not found. Please install Docker Compose first."
    exit 1
fi
echo ""

# Step 2: Setup environment for local development
echo "Step 2: Setting up environment..."
if [ ! -f .env ]; then
    echo "   ⚠ .env not found. Creating basic .env..."
    cat > .env <<EOF
# Database (Docker Compose)
DATABASE_URL=postgresql://dbis_user:dbis_password@localhost:5432/dbis_core

# Redis (Docker Compose)
REDIS_URL=redis://localhost:6379

# AS4 Configuration
AS4_BASE_URL=http://localhost:3000
AS4_LOG_LEVEL=debug
NODE_ENV=development
EOF
    echo "   ✓ .env file created"
else
    echo "   ✓ .env already exists"
    # Update DATABASE_URL for Docker Compose if needed
    if grep -q "192.168.11.105" .env; then
        echo "   ⚠ Updating DATABASE_URL for local Docker Compose..."
        sed -i.bak 's|DATABASE_URL=.*|DATABASE_URL=postgresql://dbis_user:dbis_password@localhost:5432/dbis_core|' .env
        echo "   ✓ DATABASE_URL updated for local development"
    fi
fi
echo ""

# Step 3: Generate certificates if needed
echo "Step 3: Generating certificates..."
if [ ! -f "certs/as4/as4-tls-cert.pem" ]; then
    ./scripts/generate-as4-certificates.sh
else
    echo "   ✓ Certificates already exist"
fi
echo ""

# Step 4: Create necessary directories
echo "Step 4: Creating directories..."
mkdir -p logs/as4
mkdir -p data/as4/vault
mkdir -p certs/as4
echo "   ✓ Directories created"
echo ""

# Step 5: Start Docker Compose services
echo "Step 5: Starting Docker Compose services..."
if docker compose version &> /dev/null; then
    DOCKER_COMPOSE_CMD="docker compose"
else
    DOCKER_COMPOSE_CMD="docker-compose"
fi

cd docker
if $DOCKER_COMPOSE_CMD -f docker-compose.as4.yml up -d postgres redis; then
    echo "   ✓ Docker services started"
    echo "   Waiting for services to be ready..."
    sleep 5
    
    # Wait for PostgreSQL
    echo "   Waiting for PostgreSQL..."
    for i in {1..30}; do
        if docker compose -f docker-compose.as4.yml exec -T postgres pg_isready -U dbis_user &> /dev/null; then
            echo "   ✓ PostgreSQL is ready"
            break
        fi
        if [ $i -eq 30 ]; then
            echo "   ⚠ PostgreSQL may not be ready yet"
        fi
        sleep 1
    done
    
    # Wait for Redis
    echo "   Waiting for Redis..."
    for i in {1..30}; do
        if docker compose -f docker-compose.as4.yml exec -T redis redis-cli ping &> /dev/null; then
            echo "   ✓ Redis is ready"
            break
        fi
        if [ $i -eq 30 ]; then
            echo "   ⚠ Redis may not be ready yet"
        fi
        sleep 1
    done
else
    echo "   ✗ Failed to start Docker services"
    exit 1
fi
cd ..
echo ""

# Step 6: Generate Prisma client
echo "Step 6: Generating Prisma client..."
npx prisma generate
echo "   ✓ Prisma client generated"
echo ""

# Step 7: Run database migration
echo "Step 7: Running database migration..."
if npx prisma migrate deploy; then
    echo "   ✓ Migration successful"
else
    echo "   ⚠ Migration failed - database may not be ready yet"
    echo "   Run manually: npx prisma migrate deploy"
fi
echo ""

# Step 8: Seed marketplace
echo "Step 8: Seeding marketplace offering..."
if npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts; then
    echo "   ✓ Marketplace seeded"
else
    echo "   ⚠ Seeding failed - database may not be ready yet"
    echo "   Run manually: npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts"
fi
echo ""

# Summary
echo "========================================="
echo "Local Development Setup Complete!"
echo "========================================="
echo ""
echo "Services running:"
echo "  - PostgreSQL: localhost:5432"
echo "  - Redis: localhost:6379"
echo ""
echo "Next steps:"
echo "  1. Verify setup: ./scripts/check-database-status.sh"
echo "  2. Start server: npm run dev"
echo "  3. Test endpoints: ./scripts/test-as4-api.sh"
echo ""
echo "To stop services:"
echo "  cd docker && docker compose -f docker-compose.as4.yml down"
echo ""
