#!/bin/bash

# 读取所有任务
all_issues=$(cat /tmp/all_issues_complete.json)

# 当前时间
current_time=$(date -u +%s)

# 统计各状态任务数量
echo "=== 任务状态分布 ==="
echo "$all_issues" | jq -r 'group_by(.status) | map({status: .[0].status, count: length}) | .[]' | jq -r '"\(.status): \(.count)"'

echo ""
echo "=== 未完成任务详细检查 ==="

# 过滤未完成的任务
unfinished=$(echo "$all_issues" | jq '[.[] | select(.status != "done" and .status != "cancelled" and .status != "backlog")]')

echo "$unfinished" | jq -c '.[]' | while read -r issue; do
  id=$(echo "$issue" | jq -r '.id')
  identifier=$(echo "$issue" | jq -r '.identifier')
  status=$(echo "$issue" | jq -r '.status')
  assignee_id=$(echo "$issue" | jq -r '.assignee_id // "null"')
  assignee_type=$(echo "$issue" | jq -r '.assignee_type // "null"')
  updated_at=$(echo "$issue" | jq -r '.updated_at')
  title=$(echo "$issue" | jq -r '.title')
  
  # 计算更新时间差（小时）
  updated_ts=$(date -d "$updated_at" +%s 2>/dev/null || echo "0")
  hours_since_update=$(( (current_time - updated_ts) / 3600 ))
  
  echo ""
  echo "【$identifier】 $title"
  echo "  状态: $status"
  echo "  负责人: $assignee_id ($assignee_type)"
  echo "  最后更新: $updated_at (${hours_since_update}小时前)"
  
  # 检查规则
  if [ "$status" = "in_review" ]; then
    if [ "$assignee_id" != "34d7c53d-bd70-45a8-bbbb-77dbb1da16b5" ]; then
      echo "  ❌ 问题: in_review 状态但未分配给代码评审专家"
      echo "$id|reassign|34d7c53d-bd70-45a8-bbbb-77dbb1da16b5" >> /tmp/actions.txt
    else
      echo "  ✅ 分配正确"
    fi
  elif [ "$status" = "todo" ] && [ "$assignee_id" != "null" ]; then
    if [ "$hours_since_update" -gt 2 ]; then
      echo "  ⚠️  问题: todo 状态超过2小时未更新"
      echo "$id|mention|$assignee_id" >> /tmp/actions.txt
    else
      echo "  ✅ 时间正常"
    fi
  elif [ "$status" = "in_progress" ]; then
    if [ "$hours_since_update" -gt 48 ]; then
      echo "  ⚠️  问题: in_progress 状态超过48小时未更新"
      echo "$id|mention|$assignee_id" >> /tmp/actions.txt
    else
      echo "  ✅ 时间正常"
    fi
  elif [ "$assignee_id" = "null" ]; then
    echo "  ⚠️  问题: 状态为 $status 但无负责人"
    echo "$id|comment|需要分配负责人" >> /tmp/actions.txt
  fi
done

echo ""
echo "=== 待执行操作 ==="
if [ -f /tmp/actions.txt ]; then
  cat /tmp/actions.txt
else
  echo "无需执行任何操作"
fi
