#!/bin/bash

# Build and install the new libraries

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}Building and installing new libraries...${NC}"

# Store original location
ORIGINAL_DIR=$(pwd)

# Find git root directory
GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)
if [ $? -ne 0 ]; then
    echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}"
    exit 1
fi

cd "$GIT_ROOT"

cleanup() {
    cd "$ORIGINAL_DIR"
}

# Set up cleanup on exit
trap cleanup EXIT

# Build order is important due to dependencies
libs=(
    # Core Libraries - minimal dependencies
    "core/types"           # Base types - no dependencies
    "core/logger"          # Logging utilities - depends on types
    "core/config"          # Configuration - depends on types and logger
    
    # Utils - needed by many libraries
    "utils"                # Utilities - minimal dependencies
    
    # Data access libraries
    "data/mongodb"         # MongoDB client - depends on core libs
    "data/postgres"        # PostgreSQL client - depends on core libs
    "data/questdb"         # QuestDB client - depends on core libs
    
    # Core infrastructure services
    "core/shutdown"        # Shutdown - no dependencies
    "core/cache"           # Cache - depends on core libs
    "core/event-bus"       # Event bus - depends on core libs
    "core/handler-registry" # Handler registry - depends on core libs
    "core/handlers"        # Handlers - depends on core libs, handler-registry, and utils
    "core/queue"           # Queue - depends on core libs, cache, handlers, and handler-registry
    
    # Application services  
    "services/browser"     # Browser - depends on core libs
    "services/proxy"       # Proxy manager - depends on core libs and cache
    
    # DI - dependency injection library  
    "core/di"              # Dependency injection - depends on data, service libs, and handlers
)

# Build each library in order
for lib in "${libs[@]}"; do
    lib_path="$GIT_ROOT/libs/$lib"
    
    echo -e "${GREEN}Building $lib...${NC}"
    cd "$lib_path"
    
    # Clean previous build artifacts
    rm -rf dist tsconfig.tsbuildinfo
    
    # Use tsc with build mode to respect project references
    # npx tsc -b
    bun run build
    
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to build $lib. Exiting.${NC}"
        exit 1
    fi
    
    # Verify build was successful
    if [ -d "dist" ]; then
      echo -e "${GREEN}✓ Built successfully${NC}"
    else
      echo -e "${RED}✗ Build did not create dist directory${NC}"
      exit 1
    fi
done

echo -e "${GREEN}All libraries built successfully!${NC}"
cd "$GIT_ROOT"
