#!/bin/bash
set -e

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

# Print colored message
print_message() {
  echo -e "${GREEN}[build.sh]${NC} $1"
}

print_error() {
  echo -e "${RED}[build.sh]${NC} $1"
}

print_warning() {
  echo -e "${YELLOW}[build.sh]${NC} $1"
}

# Check for required dependencies
check_dependencies() {
  print_message "Checking dependencies..."

  # Check for CMake
  if ! command -v cmake &> /dev/null; then
    print_error "CMake is not installed. Please install it using your package manager."
    exit 1
  fi

  # Check for Qt6
  if ! pkg-config --exists Qt6Core Qt6Widgets Qt6Sql; then
    print_warning "Qt6 development packages might not be installed."
    print_warning "If build fails, install Qt6 development packages using your package manager."
  fi
}

# Create build directory
create_build_dir() {
  print_message "Creating build directory..."

  if [ ! -d "build" ]; then
    mkdir -p build
  fi
}

# Configure the project
configure_project() {
  print_message "Configuring project with CMake..."

  # Clear stale cache if the source directory has changed
  if [ -f "build/CMakeCache.txt" ]; then
    cached_src=$(grep "^CMAKE_HOME_DIRECTORY:INTERNAL=" build/CMakeCache.txt | cut -d= -f2)
    current_src="$(pwd)"
    if [ "$cached_src" != "$current_src" ]; then
      print_warning "Stale CMake cache detected (was: $cached_src). Clearing build directory..."
      rm -rf build
      mkdir -p build
    fi
  fi

  cd build
  cmake ..
  cd ..
}

# Build the project
build_project() {
  print_message "Building project..."

  cd build
  make -j$(nproc)
  cd ..
}

# Run the application
run_application() {
  print_message "Running application..."

  # Check if the application exists
  if [ -f "build/orc-gallery" ]; then
    ./build/orc-gallery
  else
    print_error "Application not found. Build might have failed."
    exit 1
  fi
}

# -------- Main script execution --------
print_message "Starting build process for ORC Gallery..."

check_dependencies
create_build_dir
configure_project
build_project

print_message "Build completed successfully!"

# Ask user if they want to run the application
read -p "Do you want to run the application now? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  run_application
else
  print_message "You can run the application later using: ./build/orc-gallery"
fi
