#!/bin/bash

# --- Functions ---

# Display the main menu
display_menu() {
  clear  # Clear the screen for a clean menu
  echo "--- Project Install Console ---"
  echo "1. Reconfigure (with tests)"
  echo "2. Reconfigure (without tests)"
  echo "3. Build"
  echo "4. Run Tests"
  echo "5. Run Test with gdb (Specify test name)"
  echo "6. Wipe (Clean build directory)"
  echo "7. Generate Documentation"  # Added documentation option
  echo "8. Exit"
  echo "-------------------------------"
  echo -n "Enter your choice [1-8]: "
}

# Reconfigure the project (meson setup)
reconfigure() {
  local test_flag="$1" # Use local to avoid global variable pollution

  if [[ "$test_flag" == "true" ]]; then
    meson setup build -Dbuild_tests=true --buildtype=debug
  else
    meson setup build -Dbuild_tests=false --buildtype=release
  fi

  if [[ $? -eq 0 ]]; then  # Check exit code for success
    echo "Reconfiguration successful."
  else
    echo "Reconfiguration failed."
    return 1 # Return a non-zero exit code to signal failure
  fi
}

# Build the project
build_project() {
  meson compile -C build

  if [[ $? -eq 0 ]]; then
    echo "Build successful."
  else
    echo "Build failed."
    return 1
  fi
}

# Run tests
run_tests() {
  meson test -C build

  if [[ $? -eq 0 ]]; then
    echo "Tests passed." #  More specific message.
  else
    echo "Tests failed."
    return 1
  fi
}

# Run a specific test with GDB
run_test_gdb() {
    local test_dir="build/tests"  # Store the base test directory
    local selected_test=""
    local test_options=()
    local test_index=1
    local choice

    # --- Find test executables ---
    # Use find to get a list of potential test executables, *excluding* .p and .cpp.o files
    #  We sort it for consistent ordering.  The '-type f' ensures we only find files.
    #  The '-executable' ensures the files are actually executable.
    find "$test_dir" -type f -executable \
        ! -name "*.p" ! -name "*.cpp.o" ! -name "*.h.gch" | sort | while read -r file; do
        # Remove the 'build/tests/' prefix and the file extension
        test_name=$(basename "$file")
        test_options+=("$test_name")
        echo "$test_index. $test_name"
        test_index=$((test_index + 1))
    done

    # Check if any tests were found
    if [[ ${#test_options[@]} -eq 0 ]]; then
        echo "No test executables found in build/tests."
        return 1
    fi

    # --- Prompt for test selection ---
    echo "-------------------------------"
    echo -n "Enter the number of the test to debug (or 0 to cancel): "
    read -r choice

    # --- Input Validation ---
    if ! [[ "$choice" =~ ^[0-9]+$ ]]; then  # Check if input is a number
        echo "Invalid input. Please enter a number."
        return 1
    fi

    if [[ "$choice" -eq 0 ]]; then
        echo "Test selection cancelled."
        return 0
    fi

    if [[ "$choice" -lt 1 || "$choice" -gt ${#test_options[@]} ]]; then
        echo "Invalid test number. Please enter a number within the valid range."
        return 1
    fi

    # --- Get the selected test name ---
    selected_test="${test_options[$((choice - 1))]}" # Adjust for 0-based array indexing

    # --- Run GDB ---
    # Construct full path.  More reliable than changing directories.
    local full_test_path="$test_dir/$selected_test"

     if [[ ! -x "$full_test_path" ]]; then
        echo "Error: Test executable '$full_test_path' not found or not executable."
        return 1
    fi

    gdb --args "$full_test_path"

}

# Wipe the build directory
wipe_build() {
  echo -n "Are you sure you want to wipe the build directory? (y/N): "
  read -r confirm

  if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
    rm -rf build
    echo "Build directory wiped."
  else
    echo "Wipe cancelled."
  fi
}

generate_docs() {
    echo "Generating documentation..."
    doxygen
    if [[ $? -ne 0 ]]; then  # Check if doxygen succeeded
        echo "Error: Doxygen failed."
        return 1
    fi

    if [[ -d docs/latex ]]; then #Check if directory exist
        cd docs/latex || return #cd into docs/latex and exit the function if unsuccesful
        make
        if [[ $? -ne 0 ]]; then #Check make
           echo "Error: make in docs/latex failed."
           cd ../.. || exit #go back, or exit the script if it fails
           return 1
        fi
        cd ../.. || exit  # Go back to the project root
    else
        echo "Warning: docs/latex directory not found.  Skipping LaTeX build."
    fi
   
    echo "Documentation generated."
}

# --- Main Loop ---

while true; do
  display_menu
  read -r choice

  case "$choice" in
    1)
      reconfigure "true"
      ;;
    2)
      reconfigure "false"
      ;;
    3)
      build_project
      ;;
    4)
      run_tests
      ;;
    5)
      run_test_gdb
      ;;
    6)
      wipe_build
      ;;
    7)
      generate_docs
      ;;
    8)
      echo "Exiting..."
      break  # Exit the while loop
      ;;
    *)
      echo "Invalid choice. Please enter a number between 1 and 8."
      ;;
  esac

  echo -n "Press Enter to continue..."
  read -r  # Wait for Enter key press
done

exit 0 #Good practice