#!/bin/bash

# Build Clean Script for Stock Bot
# Clean previous builds then build everything fresh

set -e

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

echo -e "${CYAN}🧹 Clean Build Process Starting...${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 everything
echo -e "${YELLOW}🗑️  Cleaning previous builds...${NC}"
./scripts/clean.sh --dist --cache --tsbuildinfo
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Clean failed${NC}"
    exit 1
fi

# Step 2: Build everything fresh
echo -e "${GREEN}🏗️  Building everything fresh...${NC}"
./scripts/build-all.sh
if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Build failed${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Clean build completed successfully!${NC}"
echo -e "${CYAN}🚀 Project is ready for deployment.${NC}"
