#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

gitdirs=$(find . -type d -name ".git")

for gitdir in $gitdirs; do
    repo=$(dirname "$gitdir")
    cd "$repo" || continue
    echo -e "${CYAN}📁 Repository: $repo${NC}"

    # Check status
    uncommitted=$(git status --porcelain | wc -l | tr -d ' ')
    git remote update > /dev/null 2>&1
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
        ahead=$(git rev-list --count @{u}..HEAD 2>/dev/null)
        behind=$(git rev-list --count HEAD..@{u} 2>/dev/null)
    else
        ahead=0
        behind=0
    fi

    # Handle uncommitted changes
    if [ "$uncommitted" -gt 0 ]; then
        echo -e "  ${YELLOW}You have $uncommitted uncommitted change(s).${NC}"
        git status --short
        echo "  What do you want to do?"
        select action in "Commit" "Stash" "Skip"; do
            case $action in
                Commit)
                    echo "  Enter commit message:"
                    read msg
                    git add -A
                    git commit -m "$msg"
                    break
                    ;;
                Stash)
                    git stash push -u -m "Interactive stash by script"
                    break
                    ;;
                Skip)
                    echo "  Skipping uncommitted changes."
                    break
                    ;;
            esac
        done
    fi

    # Handle behind remote
    if [ "$behind" -gt 0 ]; then
        echo -e "  ${YELLOW}Your branch is behind remote by $behind commit(s).${NC}"
        echo "  Do you want to pull (rebase) now? (y/n)"
        read ans
        if [[ "$ans" =~ ^[Yy]$ ]]; then
            git pull --rebase
        fi
    fi

    # Handle unpushed commits
    if [ "$ahead" -gt 0 ]; then
        echo -e "  ${YELLOW}You have $ahead local commit(s) not pushed to remote.${NC}"
        echo "  Do you want to push now? (y/n)"
        read ans
        if [[ "$ans" =~ ^[Yy]$ ]]; then
            git push
        fi
    fi

    # Handle stashes
    stash_count=$(git stash list | wc -l | tr -d ' ')
    if [ "$stash_count" -gt 0 ]; then
        echo -e "  ${YELLOW}You have $stash_count stash(es). Do you want to pop the latest? (y/n)${NC}"
        read ans
        if [[ "$ans" =~ ^[Yy]$ ]]; then
            git stash pop
        fi
    fi

    echo -e "${CYAN}──────────────────────────────────────────────${NC}"
    cd - > /dev/null || exit
done 