#!/bin/bash
# 创建新任务脚本 - 带git容错处理
# 改进逻辑：每次创建前自动commit所有现有变更，避免unstaged changes问题

TASK_ID="TASK-$(date +%Y%m%d%H%M%S)"
TASK_FILE="management/tasks/pending/${TASK_ID}.md"

mkdir -p management/tasks/pending
echo "# 任务ID: $TASK_ID" > "$TASK_FILE"
echo "# 状态: pending" >> "$TASK_FILE"
echo "# 创建时间: $(date)" >> "$TASK_FILE"
echo "" >> "$TASK_FILE"
echo "## 任务需求" >> "$TASK_FILE"
echo "$1" >> "$TASK_FILE"

# Git处理，带容错
# 改进：每次创建前自动commit所有现有变更，解决批量创建时的unstaged changes问题
echo "🔄 正在同步现有变更..."
git add . > /dev/null 2>&1
# 如果有变更就commit
git commit -m "sync: 自动同步未提交变更 [create $TASK_ID]" > /dev/null 2>&1

echo "🔄 正在拉取最新代码..."
git pull origin main
if [ $? -ne 0 ]; then
  echo "⚠️  git pull 失败，请先解决冲突后再试"
  exit 1
fi

git add "$TASK_FILE"
git commit -m "feat: 创建新任务 $TASK_ID"
if [ $? -ne 0 ]; then
  echo "⚠️  git commit 失败"
  exit 1
fi

git push origin main
if [ $? -ne 0 ]; then
  echo "⚠️  git push 失败"
  exit 1
fi

echo "✅ 任务创建成功: $TASK_ID"
echo "📄 文件: $TASK_FILE"
echo "🌐 已推送到 Gitee"
