#!/bin/bash
# 修正版Agent监控脚本

AGENT="$1"

if [ -z "$AGENT" ]; then
  echo "使用方法: ./agent_monitor_fixed.sh <agent_name>"
  echo "例如: ./agent_monitor_fixed.sh pangtong"
  echo "支持的agent: pangtong, zhangfei, guanyu, zhaoyun, jiangwei, simayi"
  exit 1
fi

# 自动检测项目根目录
# SCRIPT_DIR: .../sanguo_quant_live/management/workflow/scripts
# 三次 dirname 回到项目根目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$(dirname "$SCRIPT_DIR")")")"
cd "$PROJECT_ROOT" || {
  echo "❌ 错误：无法进入项目目录 $PROJECT_ROOT"
  exit 1
}

LOG_FILE="${AGENT}_monitor.log"
AGENT_DIR="management/agents/${AGENT}"
mkdir -p "$AGENT_DIR"

# 函数：同时输出到stdout和日志文件
log_info() {
    echo "$1"
    echo "$1" >> "$LOG_FILE"
}

log_info "========================================="
log_info "Agent监控启动 - $AGENT"
log_info "启动时间: $(date '+%Y-%m-%d %H:%M:%S')"
log_info "监控目录: $AGENT_DIR"
log_info "检查间隔: 30秒"
log_info "自动git pull: 每次检查前自动拉取"
log_info "========================================="

echo "🚀 $AGENT Agent监控器启动"
echo "📊 监控目录: $AGENT_DIR"
echo "📝 日志文件: $LOG_FILE"
echo "⏰ 检查间隔: 30秒"
echo "🔄 自动git pull: 每次检查前自动拉取"

while true; do
  TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
  
  # 1. 自动git pull获取最新任务
  git pull origin main >> "$LOG_FILE" 2>&1
  if [ $? -eq 0 ]; then
    log_info "[$TIMESTAMP] ✅ git pull成功"
  else
    log_info "[$TIMESTAMP] ⚠️ git pull失败，继续检查"
  fi
  
  # 2. 检查是否有.task文件
  TASK_FILES=$(ls ${AGENT_DIR}/*.task 2>/dev/null)
  
  if [ -n "$TASK_FILES" ]; then
    for TASK_FILE in $TASK_FILES; do
      TASK_ID=$(basename "$TASK_FILE" .task)
      
      # 发现任务 - 同时输出到聊天窗口
      log_info "[$TIMESTAMP] 🎯 $AGENT 发现新任务: $TASK_ID"
      
      # 读取任务内容
      TASK_CONTENT=$(head -10 "$TASK_FILE" 2>/dev/null)
      echo "[$TIMESTAMP] 📋 任务内容预览:" >> "$LOG_FILE"
      echo "$TASK_CONTENT" >> "$LOG_FILE"
      
      # 读取完整任务内容
      TASK_FULL_CONTENT=$(cat "$TASK_FILE")
      
      # 自动创建完成标记
      DONE_FILE="${AGENT_DIR}/${TASK_ID}.done"
      echo "# 自动化任务完成报告" > "$DONE_FILE"
      echo "- 任务ID: $TASK_ID" >> "$DONE_FILE"
      echo "- 发现时间: $TIMESTAMP" >> "$DONE_FILE"
      echo "- 执行Agent: $AGENT" >> "$DONE_FILE"
      echo "- 当前项目目录: $(pwd)" >> "$DONE_FILE"
      echo "" >> "$DONE_FILE"
      echo "## 任务内容" >> "$DONE_FILE"
      echo "$TASK_FULL_CONTENT" >> "$DONE_FILE"
      echo "" >> "$DONE_FILE"
      echo "✅ 监控自动发现任务成功，工作流正常" >> "$DONE_FILE"
      
      # 完成任务后删除.task文件
      rm "$TASK_FILE"
      # 把删除也加入Git
      git rm "$TASK_FILE" >> "$LOG_FILE" 2>&1
      
      log_info "[$TIMESTAMP] ✅ $AGENT 完成任务: $TASK_ID"
      log_info "[$TIMESTAMP] 📝 完成标记已创建: $DONE_FILE"
      
      # 自动推送完成结果
      # 添加.done文件和已删除的.task文件
      git add "$DONE_FILE" >> "$LOG_FILE" 2>&1
      UNCOMMITTED=$(git status --porcelain | grep -E "($DONE_FILE|$TASK_FILE)" || true)
      if [ -n "$UNCOMMITTED" ]; then
        log_info "[$TIMESTAMP] 📤 正在推送完成结果..."
        git commit -m "auto: $AGENT 完成任务 $TASK_ID" >> "$LOG_FILE" 2>&1
        # 先push，如果失败，pull rebase再试一次
        git push origin main >> "$LOG_FILE" 2>&1
        if [ $? -ne 0 ]; then
          log_info "[$TIMESTAMP] ⚠️ 第一次推送失败，尝试拉取最新代码后重试..."
          git pull --rebase origin main >> "$LOG_FILE" 2>&1
          git push origin main >> "$LOG_FILE" 2>&1
          if [ $? -eq 0 ]; then
            log_info "[$TIMESTAMP] ✅ 推送成功！任务 $TASK_ID 完全完成"
          else
            log_info "[$TIMESTAMP] ❌ 推送失败，请检查Git配置"
          fi
        else
          log_info "[$TIMESTAMP] ✅ 推送成功！任务 $TASK_ID 完全完成"
        fi
      fi
    done
  else
    echo "[$TIMESTAMP] $AGENT 无新任务" >> "$LOG_FILE"
  fi
  
  # 等待30秒
  sleep 30
done