# Define the directories to check
DIRECTORIES=("agenta-backend" "agenta-cli")
ORIGINAL_DIR=$(pwd)
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
FIRST_PUSH_FILE=".git/first_push_detected"

# Function to run frontend checks
run_frontend_checks() {
    cd agenta-web || exit

    # Run ESLint check
    if ! npm run lint; then
        echo '❌ ESLint issues detected. Please fix them before pushing.'
        exit 1
    fi

    # Run TypeScript type check
    if ! npm run types:check; then
        echo '❌ TypeScript type check failed.'
        exit 1
    fi

    echo '🎉 Frontend checks passed!'
    cd "$ORIGINAL_DIR" || exit
}

# Function to run backend checks
run_backend_checks() {
    local DIR=$1
    cd "$DIR" || exit

    # Run pylint checks
    if ! pylint --recursive=y --errors-only .; then
        echo "❌ pylint issues detected in $DIR. Please fix them before pushing."
        exit 1
    fi

    echo "🎉 Backend checks passed for $DIR."
    cd "$ORIGINAL_DIR" || exit
}

# Check if this is the first push
is_first_push() {
    # Check if the branch exists locally
    if ! git rev-parse --verify "$BRANCH_NAME" >/dev/null 2>&1; then
        return 0  # First push, since the branch doesn't exist locally
    fi

    # Check if the branch exists remotely
    if ! git ls-remote --heads origin "$BRANCH_NAME" | grep -q "$BRANCH_NAME"; then
        return 0  # First push, since the branch doesn't exist remotely
    fi

    return 1  # Not the first push
}

# If: First-time push: Run all checks
# Else: Check directory-specific changes for existing branch
if is_first_push; then
    echo "🚀 First-time push detected for branch: $BRANCH_NAME"
    run_frontend_checks

    # for DIR in "${DIRECTORIES[@]}"; do
    #     run_backend_checks "$DIR"
    # done
else
    echo "🔍 Checking directory changes for existing branch: $BRANCH_NAME"
    if git diff --name-only --cached origin/"$BRANCH_NAME" | grep -q '^agenta-web/'; then
        run_frontend_checks
    fi

    # for DIR in "${DIRECTORIES[@]}"; do
    #     if git diff --name-only --cached origin/"$BRANCH_NAME" | grep -q "^$DIR/"; then
    #         run_backend_checks "$DIR"
    #     fi
    # done
fi
