#!/bin/bash

# Drift Trading Setup Script
# This script helps set up the Drift trading integration

echo "🌊 Drift Trading Integration Setup"
echo "=================================="

# Check if .env file exists
if [ ! -f .env ]; then
    echo "❌ .env file not found!"
    echo "Please create a .env file with the required environment variables."
    echo "See DRIFT_INTEGRATION.md for details."
    exit 1
fi

# Check for required environment variables
echo "🔍 Checking environment variables..."

if grep -q "SOLANA_PRIVATE_KEY" .env; then
    echo "✅ SOLANA_PRIVATE_KEY found"
else
    echo "❌ SOLANA_PRIVATE_KEY not found in .env"
    echo "Please add your Solana private key to the .env file"
    exit 1
fi

if grep -q "SOLANA_RPC_URL" .env; then
    echo "✅ SOLANA_RPC_URL found"
else
    echo "❌ SOLANA_RPC_URL not found in .env"
    echo "Please add a Solana RPC URL to the .env file"
    exit 1
fi

# Check if dependencies are installed
echo "📦 Checking dependencies..."

if npm list @drift-labs/sdk &>/dev/null; then
    echo "✅ @drift-labs/sdk installed"
else
    echo "❌ @drift-labs/sdk not found"
    echo "Installing Drift SDK..."
    npm install @drift-labs/sdk
fi

if npm list @solana/web3.js &>/dev/null; then
    echo "✅ @solana/web3.js installed"
else
    echo "❌ @solana/web3.js not found"
    echo "Installing Solana Web3.js..."
    npm install @solana/web3.js
fi

# Test the connection
echo "🧪 Testing Drift connection..."

if [ -f "test-drift-trading.js" ]; then
    echo "Running connection test..."
    
    # Start the dev server in background if not running
    if ! curl -s http://localhost:3000 &>/dev/null; then
        echo "Starting development server..."
        npm run dev &
        DEV_PID=$!
        
        # Wait for server to start
        echo "Waiting for server to start..."
        for i in {1..30}; do
            if curl -s http://localhost:3000 &>/dev/null; then
                echo "✅ Server started successfully"
                break
            fi
            sleep 1
        done
        
        if [ $i -eq 30 ]; then
            echo "❌ Server failed to start within 30 seconds"
            kill $DEV_PID 2>/dev/null
            exit 1
        fi
        
        # Run the test
        sleep 2
        node test-drift-trading.js
        
        # Stop the dev server
        kill $DEV_PID 2>/dev/null
        echo "Development server stopped"
    else
        echo "✅ Server already running"
        node test-drift-trading.js
    fi
else
    echo "❌ test-drift-trading.js not found"
    echo "Test script is missing"
fi

echo ""
echo "🎉 Setup completed!"
echo ""
echo "Next steps:"
echo "1. Make sure you have a Drift account initialized at https://app.drift.trade"
echo "2. Deposit some USDC collateral to your Drift account"
echo "3. Start the development server: npm run dev"
echo "4. Open http://localhost:3000 and check the Drift Account Status panel"
echo ""
echo "For more information, see DRIFT_INTEGRATION.md"
