#!/usr/bin/env bash
set -euo pipefail

# Extract git metrics for worklog session
# Outputs structured data about commits, files, and changes

# Check if we're in a git repo
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo "Error: Not in a git repository"
    exit 1
fi

# Get commits made today
TODAY=$(date +%Y-%m-%d)
COMMITS_TODAY=$(git log --since="$TODAY 00:00:00" --oneline | wc -l)

# Get total commits available in repo to avoid HEAD~N crash in shallow/small repos
TOTAL_COMMITS=$(git rev-list --count HEAD)

# Get files touched in recent commits (last 10 or today's commits, whichever is more)
COMMIT_COUNT=$((COMMITS_TODAY > 10 ? COMMITS_TODAY : 10))
# Clamp to actual available commits (need at least 1 commit to compare)
if [ "$COMMIT_COUNT" -ge "$TOTAL_COMMITS" ]; then
    COMMIT_COUNT=$((TOTAL_COMMITS - 1))
fi

# Only calculate diffs if we have commits to compare
if [ "$COMMIT_COUNT" -gt 0 ]; then
    FILES_TOUCHED=$(git diff --name-only HEAD~"$COMMIT_COUNT"..HEAD 2>/dev/null | sort -u | wc -l)
    LINES_STATS=$(git diff --shortstat HEAD~"$COMMIT_COUNT"..HEAD 2>/dev/null || echo "0 files changed, 0 insertions(+), 0 deletions(-)")
else
    FILES_TOUCHED=0
    LINES_STATS="0 files changed, 0 insertions(+), 0 deletions(-)"
fi

# Extract numbers from shortstat using portable sed (works on Linux/macOS/BSD)
# Handles both singular and plural forms (insertion/insertions, deletion/deletions)
INSERTIONS=$(echo "$LINES_STATS" | sed -n 's/.* \([0-9]\+\) insertion.*/\1/p')
if [ -z "$INSERTIONS" ]; then
    INSERTIONS="0"
fi

DELETIONS=$(echo "$LINES_STATS" | sed -n 's/.* \([0-9]\+\) deletion.*/\1/p')
if [ -z "$DELETIONS" ]; then
    DELETIONS="0"
fi

# Get recent commit messages
RECENT_COMMITS=$(git log --since="$TODAY 00:00:00" --oneline | head -10)

# Get branch and status info
BRANCH=$(git branch --show-current 2>/dev/null || echo "detached")
STATUS=$(git status --short 2>/dev/null)
UNCOMMITTED=$(echo "$STATUS" | wc -l | tr -d ' ')
if [ -z "$STATUS" ]; then
    UNCOMMITTED=0
fi

# Output structured data
cat <<EOF
Git Context (generated $(date)):
- Branch: $BRANCH
- Uncommitted changes: $UNCOMMITTED files
- Commits made today: $COMMITS_TODAY
- Files touched (in commits): $FILES_TOUCHED
- Lines added: +$INSERTIONS
- Lines removed: -$DELETIONS

Recent commits:
$RECENT_COMMITS
EOF

# Show uncommitted changes if any
if [ -n "$STATUS" ]; then
    echo ""
    echo "Uncommitted changes:"
    echo "$STATUS"
fi
