#!/bin/bash
set -e

echo "=========================================="
echo "  Codeflash Complete Rebuild and Test"
echo "=========================================="
echo ""

cd /Users/saga4/orgs/codeflash-internal

echo "Step 1: Stopping and removing old container..."
docker stop codeflash-unified 2>/dev/null || true
docker rm codeflash-unified 2>/dev/null || true
echo "✓ Old container removed"
echo ""

echo "Step 2: Rebuilding image..."
echo "This will take 5-10 minutes..."
docker build -f deployment/onprem-simple/Dockerfile.unified-selfcontained -t codeflash/unified:latest .
echo "✓ Image rebuilt"
echo ""

echo "Step 3: Starting new container..."
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 \
  -p 3000:3000 \
  -v codeflash-data:/var/lib/postgresql/data \
  codeflash/unified:latest

echo "✓ Container started"
echo ""

echo "Step 4: Waiting for services to start (30 seconds)..."
sleep 30

echo "Step 5: Checking service status..."
docker exec codeflash-unified supervisorctl status
echo ""

echo "Step 6: Getting API key..."
API_KEY=$(docker exec codeflash-unified psql postgresql://codeflash:codeflash@localhost:5432/codeflash -t -c "SELECT 'cf-' || key FROM cf_api_keys LIMIT 1;" | tr -d ' ')
echo "API Key: $API_KEY"

echo "Step 7: Testing CLI..."
export CODEFLASH_API_KEY=$API_KEY
export CODEFLASH_AIS_SERVER=local
export CODEFLASH_CFAPI_SERVER=local

cd /Users/saga4/orgs/optimize-me
codeflash --file src/math/computation.py --function gcd_recursive --no-pr -v

echo ""
echo "=========================================="
echo "  Test Complete!"
echo "=========================================="
