#!/usr/bin/env bash
# fix-rate-trend.sh — Fix 率趋势监控
#
# 分析 git 提交历史，按周统计 fix 率趋势。
# Fix 定义: 提交消息以 "fix" 开头（conventional commits）。
#
# 用法:
#   bash scripts/fix-rate-trend.sh           # 全量趋势
#   bash scripts/fix-rate-trend.sh 30        # 最近 30 天
#
# 目标: fix 率 < 15%（当前 ~23%）

set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

DAYS="${1:-999}"
SINCE=""
if [ "$DAYS" != "999" ]; then
  SINCE="--since=\"${DAYS} days ago\""
fi

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=========================================="
echo "  Fix Rate Trend — fix / total commits"
if [ "$DAYS" != "999" ]; then
  echo "  (Last ${DAYS} days)"
fi
echo "=========================================="
echo ""

# Collect weekly stats
declare -a WEEKS=()
declare -a TOTALS=()
declare -a FIXES=()
declare -a RATES=()

eval "git log --oneline --format='%ad|%s' --date=short $SINCE" | while IFS='|' read -r date msg; do
  echo "$date|$msg"
done | awk -F'|' '
{
  date = $1
  msg = $2
  # Get ISO week number (year-week)
  cmd = "date -d \"" date "\" +\"%G-W%V\" 2>/dev/null || date -j -f \"%Y-%m-%d\" \"" date "\" +\"%G-W%V\" 2>/dev/null"
  cmd | getline week
  close(cmd)

  total[week]++
  if (msg ~ /^fix[\(:]/ || msg ~ /^fix$/) {
    fix[week]++
  } else {
    fix[week] += 0
  }
}
END {
  n = asorti(total, sorted)
  for (i = 1; i <= n; i++) {
    w = sorted[i]
    f = fix[w] + 0
    t = total[w]
    r = (f / t) * 100
    printf "%s|%d|%d|%.1f\n", w, t, f, r
  }
}' > /tmp/fix-rate-$$.tmp

# Display results
printf "%-12s %6s %6s %8s  %s\n" "WEEK" "TOTAL" "FIX" "RATE" "BAR"
echo "------------------------------------------------------------"

ALL_TOTAL=0
ALL_FIX=0

while IFS='|' read -r week total fix rate; do
  ALL_TOTAL=$((ALL_TOTAL + total))
  ALL_FIX=$((ALL_FIX + fix))

  # Color code by rate
  bar_len=$(echo "$rate" | awk '{printf "%d", $1 / 5}')
  bar=""
  for ((i=0; i<bar_len; i++)); do bar="${bar}#"; done

  if awk "BEGIN { exit ($rate < 15) ? 1 : 0 }"; then
    if awk "BEGIN { exit ($rate < 25) ? 1 : 0 }"; then
      color=$YELLOW
    else
      color=$RED
    fi
  else
    color=$GREEN
  fi

  printf "%-12s %6d %6d " "$week" "$total" "$fix"
  echo -e "${color}${rate}%${NC}  ${bar}"
done < /tmp/fix-rate-$$.tmp

rm -f /tmp/fix-rate-$$.tmp

echo "------------------------------------------------------------"
ALL_RATE=$(awk "BEGIN { printf \"%.1f\", ($ALL_FIX / $ALL_TOTAL) * 100 }")
echo ""
echo -e "Total: ${ALL_TOTAL} commits, ${ALL_FIX} fixes, rate: ${ALL_RATE}%"
echo ""

# Category breakdown for the most recent period
echo "=========================================="
echo "  Fix Category Breakdown (recent)"
echo "=========================================="

eval "git log --oneline --format='%s' $SINCE" | grep -iE "^fix" | \
  sed -E 's/^fix\([^)]*\):? ?//' | \
  grep -oE '(permission|auth|安全|security|tenant|CORS|SQL|XSS|前端|后端|接口|字段|API|路由|route|menu|菜单|编译|compile|类型|type|migration|迁移|race|竞态|token|event|事件|login|登录|miniprogram|小程序|Taro|media|轮播|banner)' | \
  sort | uniq -c | sort -rn | head -15

echo ""
echo "Target: fix rate < 15%"
echo "Red line: fix rate > 20% triggers review (see CLAUDE.md)"
