#!/bin/bash

# Build All Script for Stock Bot
# Builds libraries first, then apps with Turbo, then dashboard with Angular CLI

set -e

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

# Default options
CLEAN=false
VERBOSE=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --clean|-c)
            CLEAN=true
            shift
            ;;
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--clean] [--verbose]"
            echo "  --clean, -c    Clean previous builds before building"
            echo "  --verbose, -v  Show verbose output"
            echo "  --help, -h     Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

echo -e "${CYAN}🚀 Starting complete build process...${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

# Step 1: Clean if requested
if [ "$CLEAN" = true ]; then
    echo -e "${YELLOW}🧹 Cleaning previous builds...${NC}"
    ./scripts/clean.sh --dist
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Clean failed${NC}"
        exit 1
    fi
fi

# Step 2: Build libraries first
echo -e "${GREEN}📚 Building libraries...${NC}"
./scripts/build-libs.sh
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Library build failed${NC}"
    exit 1
fi

# Step 3: Build apps with Turbo (excluding dashboard)
echo -e "${GREEN}🏗️ Building applications with Turbo...${NC}"

# Get list of apps excluding dashboard
if [ -d "apps" ]; then
    app_dirs=$(find apps -maxdepth 1 -type d -name "*" ! -name "dashboard" ! -name "apps" | sort)
    
    if [ -n "$app_dirs" ]; then
        # Build each app individually to avoid filter syntax issues
        for app_dir in $app_dirs; do
            app_name=$(basename "$app_dir")
            app_path="./apps/$app_name"
            echo -e "${CYAN}  Building $app_name...${NC}"
            
            turbo_cmd="turbo run build --filter=$app_path"
            
            if [ "$VERBOSE" = true ]; then
                echo -e "${GRAY}  Running: $turbo_cmd${NC}"
            fi
            
            eval $turbo_cmd
            if [ $? -ne 0 ]; then
                echo -e "${RED}❌ Failed to build app: $app_name${NC}"
                exit 1
            fi
        done
        
        app_names=$(echo "$app_dirs" | xargs -n1 basename | tr '\n' ', ' | sed 's/,$//')
        echo -e "${GREEN}✅ Apps built successfully: $app_names${NC}"
    else
        echo -e "${YELLOW}ℹ️ No non-dashboard apps found to build with Turbo${NC}"
    fi
fi

# Step 4: Build dashboard with Angular CLI
dashboard_path="apps/dashboard"
if [ -d "$dashboard_path" ]; then
    echo -e "${GREEN}🎨 Building Angular dashboard...${NC}"
    
    cd "$dashboard_path"
    
    # Check if ng is available
    if ! command -v ng &> /dev/null; then
        echo -e "${RED}❌ Angular CLI not found. Installing...${NC}"
        npm install -g @angular/cli
        if [ $? -ne 0 ]; then
            echo -e "${RED}❌ Failed to install Angular CLI${NC}"
            exit 1
        fi
    fi
    
    # Build dashboard
    ng build --configuration production
    if [ $? -ne 0 ]; then
        echo -e "${RED}❌ Dashboard build failed${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Dashboard built successfully${NC}"
    cd "$ORIGINAL_DIR"
else
    echo -e "${YELLOW}⚠️ Dashboard not found at $dashboard_path${NC}"
fi

echo -e "${GREEN}🎉 Complete build finished successfully!${NC}"
echo ""
echo -e "${CYAN}Build Summary:${NC}"
echo -e "${GREEN}  ✅ Libraries built${NC}"
if [ -n "$app_dirs" ]; then
    echo -e "${GREEN}  ✅ Apps built: $app_names${NC}"
fi
if [ -d "apps/dashboard" ]; then
    echo -e "${GREEN}  ✅ Dashboard built${NC}"
fi
