#!/usr/bin/env bash
# git_repo_status
# ---------------
# Muestra el estado completo de un repositorio Git: rama actual, upstream,
# cambios pendientes, stash, remotes y últimos commits.
# Sale con exit code 1 si el directorio actual no es un repositorio Git.
#
# USO:
#   source git_repo_status.sh
#   git_repo_status
#
# O como script directo:
#   bash git_repo_status.sh

git_repo_status() {
    if ! git rev-parse --is-inside-work-tree &>/dev/null; then
        echo "git_repo_status: el directorio actual no es un repositorio Git" >&2
        return 1
    fi

    local branch
    branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"

    # Upstream
    local upstream
    upstream="$(git rev-parse --abbrev-ref "${branch}@{upstream}" 2>/dev/null || echo "")"
    local upstream_info
    if [[ -z "$upstream" ]]; then
        upstream_info="sin upstream"
    else
        local ahead behind
        ahead="$(git rev-list "${upstream}..HEAD" --count 2>/dev/null || echo 0)"
        behind="$(git rev-list "HEAD..${upstream}" --count 2>/dev/null || echo 0)"
        upstream_info="↑${ahead} ↓${behind} (${upstream})"
    fi

    echo "=== Rama & Upstream ==="
    echo "  Rama actual:  ${branch}"
    echo "  Upstream:     ${upstream_info}"
    echo ""

    # Cambios
    echo "=== Cambios ==="
    local changes
    changes="$(git status --short 2>/dev/null)"
    if [[ -z "$changes" ]]; then
        echo "  Directorio de trabajo limpio"
    else
        echo "  Cambios pendientes:"
        echo "$changes" | while IFS= read -r line; do
            echo "    ${line}"
        done
    fi
    echo ""

    # Stash
    echo "=== Stash ==="
    local stash_count
    stash_count="$(git stash list 2>/dev/null | wc -l | tr -d ' ')"
    if [[ "$stash_count" -eq 0 ]]; then
        echo "  Sin entradas en stash"
    else
        echo "  ${stash_count} entrada(s) en stash:"
        git stash list | head -5 | while IFS= read -r line; do
            echo "    ${line}"
        done
    fi
    echo ""

    # Remotes
    echo "=== Remotes ==="
    local remotes
    remotes="$(git remote -v 2>/dev/null | grep '(fetch)' || true)"
    if [[ -z "$remotes" ]]; then
        echo "  Sin remotes configurados"
    else
        echo "$remotes" | while IFS= read -r line; do
            local name url
            name="$(echo "$line" | awk '{print $1}')"
            url="$(echo "$line" | awk '{print $2}')"
            echo "  ${name} → ${url}"
        done
    fi
    echo ""

    # Últimos commits
    echo "=== Últimos commits ==="
    git log --oneline --decorate --color=always -8 2>/dev/null || true
    echo ""
}

# Ejecutar si se invoca directamente
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    git_repo_status "$@"
fi
