#!/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

# TODO: enably mypy after adding type annotations
# 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

FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g' | { grep -E "\.py$" || test $? = 1; })

[ -z "$FILES" ] && print_message "no python files in commit to format and lint" -1 "" true && exit 0

command_available "ruff"
print_message "running ruff  linting" 1 "INFO" true
echo "$FILES" | xargs ruff --fix

command_available "black"
print_message "black autoformatting" 1 "INFO" true
echo "$FILES" | xargs black --stdin-filename {}

echo "$FILES" | xargs git add
