#!/bin/bash
set -e

echo "=========================================="
echo "  Codeflash Fresh Deployment"
echo "=========================================="
echo ""

# Get repository root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

cd "$REPO_ROOT"

echo "Repository: $REPO_ROOT"
echo ""

# Step 1: Clean up
echo "Step 1: Cleaning up existing containers..."
echo "-------------------------------------------"
docker stop codeflash-unified 2>/dev/null && echo "✓ Stopped existing container" || echo "→ No existing container to stop"
docker rm codeflash-unified 2>/dev/null && echo "✓ Removed existing container" || echo "→ No existing container to remove"
docker volume rm codeflash-data 2>/dev/null && echo "✓ Removed data volume" || echo "→ No existing data volume to remove"
echo ""

# Step 2: Build
echo "Step 2: Building unified container..."
echo "-------------------------------------------"
echo "This will take 5-10 minutes on first build..."
echo ""

docker build -f deployment/onprem-simple/Dockerfile.unified-selfcontained \
  -t codeflash/unified:latest .

echo ""
echo "✓ Build complete!"
echo ""

# Step 3: Run
echo "Step 3: Starting container..."
echo "-------------------------------------------"

docker run -d --name codeflash-unified \
  -e OPENAI_API_TYPE=azure \
  -e AZURE_OPENAI_API_KEY=dabd9790e9a54558b4ceafdd74425904 \
  -e ANTHROPIC_API_KEY=sk-ant-api03-E85T16Zy7bGRo1BxVdFUJG_JRMVdMaePuLUJMFO-EQHqI17z0lWMYRHaHKUU47XeNNwZNHl86h1p-Yoq5vVgzg \
  -e SECRET_KEY=bla \
  -e NODE_ENV=local \
  -e GH_APP_ID=800528 \
  -e GH_APP_USER_ID=148906541 \
  -e GH_APP_WEBHOOK_SECRET=dev-webhook-secret-2pjGGmaNy2gyEY4o3aU \
  -e STRIPE_SECRET_KEY=sk_test_51Pap5bRrNDfNWAM0DpQb8D8sCSYxG9aFzc9N5wXN8pVT0fXLQwrJgZEZq1aRoQ9VZgVK7pXKp5aWQZYW7vXKp00aZX5aWQ \
  -p 5432:5432 \
  -p 8000:8000 \
  -p 3001:3001 \
  -v codeflash-data:/var/lib/postgresql/data \
  codeflash/unified:latest

echo ""
echo "✓ Container started!"
echo ""

# Step 4: Wait for services to start
echo "Step 4: Waiting for services to start..."
echo "-------------------------------------------"
echo "This may take 15-30 seconds..."
echo ""

sleep 10

# Wait for the API key file to be created (indicates initialization is complete)
for i in {1..30}; do
  if docker exec codeflash-unified test -f /app/API_KEY.txt 2>/dev/null; then
    break
  fi
  echo "  Waiting for database initialization... ($i/30)"
  sleep 2
done

echo ""

# Step 5: Verify services
echo "Step 5: Verifying services..."
echo "-------------------------------------------"

# Wait a bit more for services to fully start
sleep 5

docker exec codeflash-unified supervisorctl status

echo ""

# Step 6: Show API key
echo "=========================================="
echo "  ✓ DEPLOYMENT COMPLETE!"
echo "=========================================="
echo ""

API_KEY=$(docker exec codeflash-unified cat /app/API_KEY.txt 2>/dev/null || echo "API key not yet generated")

if [ "$API_KEY" != "API key not yet generated" ]; then
  echo "Your API Key: $API_KEY"
  echo ""
  echo "To use the CLI, run these commands:"
  echo ""
  echo "  cd /Users/saga4/orgs/optimize-me"
  echo "  export CODEFLASH_API_KEY=$API_KEY"
  echo "  export CODEFLASH_AIS_SERVER=local"
  echo "  export CODEFLASH_CFAPI_SERVER=local"
  echo "  codeflash --file src/math/computation.py --function gcd_recursive --no-pr -v"
  echo ""
else
  echo "Services are still initializing. View logs with:"
  echo "  docker logs -f codeflash-unified"
  echo ""
  echo "Once you see 'CODEFLASH SETUP COMPLETE!', retrieve your API key with:"
  echo "  docker exec codeflash-unified cat /app/API_KEY.txt"
  echo ""
fi

echo "=========================================="
echo ""
echo "Useful commands:"
echo "  View logs:      docker logs -f codeflash-unified"
echo "  Restart:        docker restart codeflash-unified"
echo "  Stop:           docker stop codeflash-unified"
echo "  Check services: docker exec codeflash-unified supervisorctl status"
echo ""