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

# Suggest a worklog filename based on recent git activity
# Analyzes commit messages to extract a descriptive topic

# 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 today's date
TODAY=$(date +%Y-%m-%d)

# Get recent commit messages from today
COMMIT_MESSAGES=$(git log --since="$TODAY 00:00:00" --pretty=format:"%s" | head -10)

if [ -z "$COMMIT_MESSAGES" ]; then
    # No commits today, check last few commits
    COMMIT_MESSAGES=$(git log --oneline -5 | cut -d' ' -f2-)
fi

# Extract common words (excluding common prefixes like fix, add, update)
# Convert to kebab-case topic suggestion
TOPIC=$(echo "$COMMIT_MESSAGES" \
    | tr '[:upper:]' '[:lower:]' \
    | sed 's/[^a-z0-9 ]/ /g' \
    | tr -s ' ' \
    | sed 's/^fix //g; s/^add //g; s/^update //g; s/^feat //g; s/^refactor //g' \
    | tr ' ' '\n' \
    | grep -v -E '^(and|the|for|with|from|to|in|on|at|by|of|a|an)$' \
    | sort | uniq -c | sort -rn \
    | head -3 \
    | awk '{print $2}' \
    | tr '\n' '-' \
    | sed 's/-$//')

# If no topic extracted, use generic
if [ -z "$TOPIC" ]; then
    TOPIC="work-session"
fi

# Construct filename
FILENAME="docs/worklogs/${TODAY}-${TOPIC}.md"

echo "$FILENAME"
