/**
 * Reflector - 评估操作结果，更新目标状态
 */

const { logger } = require('../../src/utils/logger')

const log = logger.child('Ambient:Reflector')

class Reflector {
  constructor(goalManager) {
    this._goalManager = goalManager
  }

  /**
   * 评估操作结果
   * @param {Object} goal - 目标对象
   * @param {Object} actionResult - 操作结果
   * @returns {Object} 评估结果 { shouldContinue, goalComplete, actionTaken }
   */
  evaluateOutcome(goal, actionResult) {
    if (!goal) return null

    // 检查是否是事件驱动目标
    const isEventDriven = goal.conditions?.events && goal.conditions.events.length > 0

    // 检查错误
    if (actionResult && actionResult.error) {
      // 增加尝试次数但不立即失败
      goal.attempts++
      // 事件驱动目标：错误不导致失败或完成
      if (isEventDriven) {
        return { shouldContinue: true, goalComplete: false }
      }
      return {
        shouldContinue: goal.attempts < goal.maxAttempts,
        actionTaken: false
      }
    }

    // 检查是否成功完成
    if (actionResult && actionResult.success === true) {
      goal.attempts++

      // 事件驱动目标：永远不会完成，持续等待下一事件
      if (isEventDriven) {
        return { shouldContinue: true, goalComplete: false }
      }

      // 检查目标是否完成
      if (goal.actions.length === 0 || goal.attempts >= goal.maxAttempts) {
        return { shouldContinue: false, goalComplete: true }
      }

      return { shouldContinue: true, actionTaken: true }
    }

    // 工具执行无错误 - 视为成功
    goal.attempts++

    // 事件驱动目标：永远不会完成
    if (isEventDriven) {
      return { shouldContinue: true, goalComplete: false }
    }

    // 检查目标是否完成（没有更多操作）
    if (goal.actions.length === 0 || goal.attempts >= goal.maxAttempts) {
      return { shouldContinue: false, goalComplete: true }
    }

    return { shouldContinue: true, actionTaken: true }
  }

  /**
   * 检查循环检测
   * @param {Object} goal - 目标对象
   * @param {string} actionId - 操作ID
   * @returns {boolean} 是否检测到循环
   */
  checkLoopDetection(goal, actionId) {
    // 如果同一操作连续重复3次，则目标失败
    if (goal.lastActionId === actionId) {
      goal.consecutiveSameActions++
      if (goal.consecutiveSameActions >= 3) {
        this._goalManager.failGoal(goal.id, '检测到循环：同一操作连续重复3次')
        return true
      }
    } else {
      goal.consecutiveSameActions = 1
      goal.lastActionId = actionId
    }
    return false
  }
}

module.exports = { Reflector }
