#!/bin/bash

set -e

# Get script directory and project root
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"

# Verify we're in the right directory
if [ ! -f "$PROJECT_ROOT/backend/go.mod" ] && [ ! -f "$PROJECT_ROOT/go.mod" ]; then
    # Try current directory if script dir detection fails
    if [ -f "backend/go.mod" ] || [ -f "go.mod" ]; then
        PROJECT_ROOT="$(pwd)"
    else
        echo "Error: Could not find project root. Please run from explorer-monorepo directory."
        exit 1
    fi
fi

cd "$PROJECT_ROOT"

echo "Starting ChainID 138 Explorer Platform in development mode..."
echo "Project root: $PROJECT_ROOT"

# Check requirements first
echo "Checking requirements..."
if ! "$SCRIPT_DIR/check-requirements.sh"; then
    echo "Please install missing requirements and try again."
    exit 1
fi
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo "Warning: .env file not found. Creating from .env.example..."
    if [ -f .env.example ]; then
        cp .env.example .env
        echo "Created .env from .env.example - please update with your configuration"
    else
        echo "Warning: .env.example not found. Using defaults."
    fi
fi

# Start infrastructure
echo "Starting infrastructure services..."
docker-compose -f deployment/docker-compose.yml up -d postgres elasticsearch redis

# Wait for services
echo "Waiting for services to be ready..."
sleep 10

# Run migrations
echo "Running database migrations..."
cd backend
go run database/migrations/migrate.go || echo "Migration failed or already applied"
cd ..

# Start indexer in background
echo "Starting indexer..."
cd backend/indexer
go run main.go &
INDEXER_PID=$!
cd ../..

# Start API server in background
echo "Starting API server..."
cd backend/api/rest
go run main.go &
API_PID=$!
cd ../../..

# Start frontend
echo "Starting frontend..."
cd frontend
npm run dev &
FRONTEND_PID=$!
cd ..

echo "All services started!"
echo "Indexer PID: $INDEXER_PID"
echo "API PID: $API_PID"
echo "Frontend PID: $FRONTEND_PID"
echo ""
echo "Press Ctrl+C to stop all services"

# Wait for user interrupt
cleanup() {
    echo ""
    echo "Stopping services..."
    kill $INDEXER_PID $API_PID $FRONTEND_PID 2>/dev/null || true
    echo "Services stopped."
    exit 0
}

trap cleanup INT TERM

# Wait for all background processes
wait

