#!/usr/bin/env bash

OMERON_MODULE_DIR="${OMERON_MODULE_DIR:-$OMERON_PROJECT_DIR/modules}"
export OMERON_MODULE_DIR

module_list() {
  local category="${1:-}"

  if [[ -n "$category" ]]; then
    find "$OMERON_MODULE_DIR/$category" -maxdepth 1 -name '*.sh' -type f | sort
  else
    find "$OMERON_MODULE_DIR" -name '*.sh' -type f | sort
  fi
}

module_run() {
  local module_path="$1"
  local module_name
  module_name="$(basename "$module_path" .sh)"

  if [[ ! -f "$module_path" ]]; then
    log_error "Module not found: $module_path"
    return 1
  fi

  log_info "Running module: $module_name"
  OMERON_CURRENT_MODULE="$module_name" source "$module_path"

  if declare -F "module_main" >/dev/null 2>&1; then
    module_main
    local rc=$?
    if [[ $rc -eq 0 ]]; then
      log_success "Module '$module_name' completed"
    else
      log_error "Module '$module_name' failed (exit: $rc)"
    fi
    return $rc
  else
    log_error "Module '$module_name' has no module_main function"
    return 1
  fi
}

module_check_prereqs() {
  local module_path="$1"

  if ! declare -F "module_prereqs" >/dev/null 2>&1; then
    return 0
  fi

  module_prereqs
}

module_skip() {
  local module_path="$1"

  if declare -F "module_should_skip" >/dev/null 2>&1; then
    module_should_skip
    return $?
  fi

  return 1
}

module_describe() {
  local module_path="$1"

  if declare -F "module_description" >/dev/null 2>&1; then
    module_description
  else
    basename "$module_path" .sh
  fi
}

module_confirm() {
  local module_path="$1"
  local description
  description="$(module_describe "$module_path")"

  if declare -F "module_required" >/dev/null 2>&1 && module_required; then
    return 0
  fi

  tui_confirm "Run '$description'?"
}
