#!/usr/bin/env bash
set -eu

print_message() {
    padding_char=">"
    message=$1
    indent_level="${2:-1}"
    level=${3:-NOCOLOR}
    prepend_newline=${4:-false}
    case "$level" in
    "INFO")
        color='\033[1;32m'
        ;;
    "WARNING")
        color='\033[1;33m'
        ;;
    "ERROR")
        color='\033[1;31m'
        ;;
    *)
        color='\033[1;37m'
        ;;
    esac
    if [[ $prepend_newline == true ]]; then printf '%b\n'; fi
    printf "${color}%s %s\n\033[0;37m" "$(printf "${padding_char}%.0s" $(seq 1 "$indent_level"))" "pre-commit hook: ${message}"
    printf '%b\n' # trailing newline
}

command_available() {
    command="$1"
    if ! command -v "$command" &>/dev/null; then
        print_message "ERROR: ${command} could not be found - commit aborted" 2 "ERROR" true
        exit 1
    fi
}

# DO NOT RUN PRE-COMMIT HOOK WHEN REBASING
BRANCH_NAME=$(git branch | grep '*' | sed 's/* //')
if [[ $BRANCH_NAME == *"no branch"* ]]
then
  exit 0
fi


command_available "mypy"
print_message "running mypy static type checking" 1 "" true
if ! mypy src;then
    print_message "mypy static type check failed - commit aborted" 1 "ERROR" true
    exit 1
fi

command_available "black"
print_message "black autoformatting" 1 "INFO" true
black .

command_available "ruff"
print_message "running ruff linting with --fix" 1 "INFO" true
ruff check --fix .

git add -u #  stages modifications and deletions, without new files
