#!/bin/bash
# pr-engagement-stats.sh

USERNAME="${GH_USERNAME:-$(gh api user --jq '.login')}"

echo "=== PR Engagement Stats for $USERNAME ==="
echo ""

# Use GraphQL for accurate data
QUERY='{
  user(login: "'"$USERNAME"'") {
    pullRequests(first: 100, states: [OPEN, CLOSED, MERGED]) {
      nodes {
        comments(first: 100) {
          nodes {
            author { login }
          }
        }
        reviews(first: 100) {
          nodes {
            author { login }
            state
          }
        }
      }
    }
  }
}'

RESULT=$(gh api graphql -f query="$QUERY" 2>/dev/null)

if [ -z "$RESULT" ] || [ "$RESULT" = "null" ]; then
    echo "❌ Failed to fetch data. Check gh authentication."
    exit 1
fi

# Count comments by you
COMMENTS=$(echo "$RESULT" | jq --arg user "$USERNAME" '
  [.data.user.pullRequests.nodes[].comments.nodes[] | 
   select(.author.login == $user)] | length
')

# Count reviews by you
REVIEWS=$(echo "$RESULT" | jq --arg user "$USERNAME" '
  [.data.user.pullRequests.nodes[].reviews.nodes[] | 
   select(.author.login == $user)] | length
')

# Count review types
APPROVED=$(echo "$RESULT" | jq --arg user "$USERNAME" '
  [.data.user.pullRequests.nodes[].reviews.nodes[] | 
   select(.author.login == $user and .state == "APPROVED")] | length
')

CHANGES_REQUESTED=$(echo "$RESULT" | jq --arg user "$USERNAME" '
  [.data.user.pullRequests.nodes[].reviews.nodes[] | 
   select(.author.login == $user and .state == "CHANGES_REQUESTED")] | length
')

echo "📊 Engagement Metrics:"
echo "   PR Comments: $COMMENTS"
echo "   Formal Reviews: $REVIEWS"
echo "     - Approved: $APPROVED"
echo "     - Changes Requested: $CHANGES_REQUESTED"
echo ""

# Ratio
if [ "$REVIEWS" -gt 0 ]; then
    RATIO=$(echo "scale=2; $COMMENTS / $REVIEWS" | bc)
    echo "📈 Comment/Review Ratio: $RATIO"
    
    TOTAL=$((COMMENTS + REVIEWS))
    COMMENT_PCT=$(echo "scale=1; $COMMENTS * 100 / $TOTAL" | bc)
    REVIEW_PCT=$(echo "scale=1; $REVIEWS * 100 / $TOTAL" | bc)
    
    echo "   Comments: ${COMMENT_PCT}%"
    echo "   Reviews: ${REVIEW_PCT}%"
else
    echo "📈 Comment/Review Ratio: N/A (no reviews)"
fi

echo ""
echo "Generated: $(date)"
