#! /bin/bash -eu

GIT_ROOT=$(git rev-parse --show-toplevel)

# Disable shellcheck false warning as it assumes incorrect path of `activate`.
# shellcheck disable=SC1091

if [[ -z "${VIRTUAL_ENV:-""}" ]]; then
    source "$GIT_ROOT/.venv/bin/activate"
fi

# Always use the latest Pyright.
export PYRIGHT_PYTHON_FORCE_VERSION=latest

# Ensure we have the latest code from the repository.
git fetch origin > /dev/null

# Reformat changed Python code. No need to check uncommitted files.
CHANGED_PY=$(git diff HEAD origin/main --name-only | grep "\.py$" || echo "")
for file in $CHANGED_PY; do
    if [ -f "$file" ]; then
        # Ensure the script continues after yapf --diff
        yapf --diff "$file" || true
        yapf --parallel --in-place --print-modified "$file"
        isort "$file"

        # Ensure Pylint continues after linting errors.
        # Ignore long lines with URLs.
        pylint "$file" \
            --rcfile="$GIT_ROOT/.pylintrc" \
            --ignore-long-lines='^\s*(# .*)?<?https?://\S+>?$' \
            --score=no \
            --jobs=0 \
        || true
    fi
done

# Type Check and lint all Python code.
pyright "$GIT_ROOT" \
    --project="$GIT_ROOT/.pyrightconfig.json" \
    --venvpath="$VIRTUAL_ENV"

# Check and remove trailing spaces.
## Exclude Markdown which allows trailing spaces.
FILES=$(git ls-files './*' | grep -Ev '\.md$|images/*')
TRAILING_SPACES=$(echo "$FILES" | xargs grep -lE " +$" || echo "")

if [ -n "$TRAILING_SPACES" ]; then
    echo "Removing trailing spaces in:"
    echo "$TRAILING_SPACES" | xargs grep -En " +$"
    echo "$TRAILING_SPACES" | xargs sed -i -e 's/[ \t]*$//'
fi

# Exit 1 if anything has changed.
git diff --quiet --
exit $?
