#!/bin/bash

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

# Arrays for summary
repos=()
uncommitted_counts=()
ahead_counts=()
behind_counts=()

total_uncommitted=0
total_ahead=0

# Find all git repos (POSIX compatible)
gitdirs=$(find . -type d -name ".git")

for gitdir in $gitdirs; do
    repo=$(dirname "$gitdir")
    cd "$repo" || continue

    echo -e "${CYAN}📁 Repository: $repo${NC}"

    # Latest 2 commits
    echo -e "  ${YELLOW}📜 Latest 2 commits:${NC}"
    git --no-pager log --oneline -2 --decorate

    # Uncommitted file count
    uncommitted=$(git status --porcelain | wc -l | tr -d ' ')
    if [ "$uncommitted" -eq 0 ]; then
        echo -e "  ${GREEN}✅ Uncommitted files: $uncommitted${NC}"
    else
        echo -e "  ${RED}🗂️ Uncommitted files: $uncommitted${NC}"
    fi

    # Check for unpushed commits
    git remote update > /dev/null 2>&1
    # Only check if upstream exists
    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
    if [ "$ahead" -gt 0 ]; then
        echo -e "  ${YELLOW}⬆️  Locally committed (not pushed): $ahead commit(s)${NC}"
    else
        echo -e "  ${GREEN}✅ All local commits are pushed${NC}"
    fi
    if [ "$behind" -gt 0 ]; then
        echo -e "  ${RED}⚠️  Behind remote by $behind commit(s)${NC}"
    fi

    echo -e "${CYAN}──────────────────────────────────────────────${NC}"

    # Store for summary
    repos+=("$repo")
    uncommitted_counts+=("$uncommitted")
    ahead_counts+=("$ahead")
    behind_counts+=("$behind")

    # Add to totals
    total_uncommitted=$((total_uncommitted + uncommitted))
    total_ahead=$((total_ahead + ahead))

    cd - > /dev/null || exit
done

# Print summary table
printf "\n${CYAN}📊 Summary Table${NC}\n"
printf "${YELLOW}%-35s │ %-13s │ %-11s │ %-8s${NC}\n" "Repository" "🗂️ Uncommitted" "⬆️ Unpushed" "⚠️ Behind"
printf "%0.s─" {1..75}; printf "\n"
for i in "${!repos[@]}"; do
    repo="${repos[$i]}"
    uncommitted="${uncommitted_counts[$i]}"
    ahead="${ahead_counts[$i]}"
    behind="${behind_counts[$i]}"
    printf "%-35s │ %-13s │ %-11s │ %-8s\n" "$repo" "$uncommitted" "$ahead" "$behind"
done

# Print overall totals
printf "%0.s─" {1..75}; printf "\n"
printf "${GREEN}🟢 Overall: ${NC}🗂️ %d uncommitted file(s), ⬆️ %d unpushed commit(s)\n" "$total_uncommitted" "$total_ahead" 