#!/bin/bash

# Check if there are modifications in the Python files
if git diff --name-only --cached | grep -q "\.py$"; then
    # If Python files are modified
    echo "Python files were modified. Running formatting..."
    if [ -x "$(command -v black)" ]; then
        python_files=$(find . -name "*.py")
        cached_python_files=$(git diff --name-only --cached | grep "\.py$")

        if [ -n "$python_files" ]; then
            black -l 120 $python_files
            for file in $cached_python_files; do
                if [ -f "$file" ]; then
                    git add $file
                fi
            done
        fi
    else
        echo "black is not installed"
        exit 1
    fi
fi

# Check if there are modifications in the frontend or docs directory
if git diff --name-only --cached | grep -E -q "^(frontend/|docs/)"; then
    # If frontend directory is modified
    echo "Frontend and/or docs files were modified. Running linting..."
    cached_frontend_or_docsfiles=$(git diff --name-only --cached | grep -E "^(frontend/|docs)")

    # Check the operating system
    if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" || "$OSTYPE" == "win32" ]]; then
        if where npm &>/dev/null; then
            for file in $cached_frontend_or_docsfiles; do
                if [ -f "$file" ] && [[ "$file" =~ \.(js|ts|vue)$ ]]; then
                    npx eslint --fix $file
                    npx prettier --write $file
                    git add $file
                fi
            done
        else
            echo "npm is not installed"
            exit 1
        fi
    else
        if [ -x "$(command -v npm)" ]; then
            for file in $cached_frontend_or_docsfiles; do
                if [ -f "$file" ] && [[ "$file" =~ \.(js|ts|vue)$ ]]; then
                    npx eslint --fix $file
                    npx prettier --write $file
                    git add $file
                fi
            done
        else
            echo "npm is not installed"
            exit 1
        fi
    fi
fi
