/**
 * EventWatcher - 订阅框架事件，筛选相关事件
 */

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

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

class EventWatcher {
  constructor(goalManager, framework) {
    this._goalManager = goalManager
    this._framework = framework
    this._handlers = []
    this._relevantEvents = new Set(DefaultEvents)
  }

  /**
   * 启动事件监听
   */
  start() {
    const events = [
      ['tool:result', (data) => this._handleEvent('tool:result', data)],
      ['scheduler:reminder', (data) => this._handleEvent('scheduler:reminder', data)],
      ['agent:message', (data) => this._handleEvent('agent:message', data)],
      ['think:thought_completed', (data) => this._handleEvent('think:thought_completed', data)],
      ['scheduler:task_completed', (data) => this._handleEvent('scheduler:task_completed', data)],
      ['scheduler:task_failed', (data) => this._handleEvent('scheduler:task_failed', data)],
      ['email:received', (data) => this._handleEvent('email:received', data)],
      ['webhook:received', (data) => this._handleEvent('webhook:received', data)]
    ]

    for (const [event, handler] of events) {
      this._framework.on(event, handler)
      this._handlers.push({ event, handler })
    }
  }

  /**
   * 停止事件监听
   */
  stop() {
    for (const { event, handler } of this._handlers) {
      this._framework.off(event, handler)
    }
    this._handlers = []
  }

  /**
   * 处理事件
   * @param {string} type - 事件类型
   * @param {Object} data - 事件数据
   */
  _handleEvent(type, data) {
    const activeGoals = this._goalManager.getActiveGoals()
    // log.info(`_handleEvent: type=${type}, activeGoals=${activeGoals.length}`)

    for (const goal of activeGoals) {
      // 检查目标条件是否匹配此事件
      const isRelevant = this._isRelevantToGoal(goal, type, data)
      // log.info(`goal=${goal.id}, isRelevant=${isRelevant}, conditions=${JSON.stringify(goal.conditions)}`)

      if (isRelevant) {
        // 将 data 展平到事件对象中，方便通过 {{_event.xxx}} 访问
        this._goalManager.addEventToGoal(goal.id, { type, ...data })
        // log.info(`Event added to goal ${goal.id}`)
      }
    }

    // 检查是否有 pending 目标需要激活
    const pendingGoals = this._goalManager.getPendingGoals()
    for (const goal of pendingGoals) {
      if (this._isRelevantToGoal(goal, type, data)) {
        // 激活目标
        this._goalManager.activateGoal(goal.id)
        // 添加事件
        this._goalManager.addEventToGoal(goal.id, { type, ...data })
        // log.info(`事件触发激活目标: ${goal.id} (事件: ${type})`)
      }
    }
  }

  /**
   * 检查事件是否与目标相关
   * @param {Object} goal - 目标对象
   * @param {string} eventType - 事件类型
   * @param {Object} data - 事件数据
   * @returns {boolean} 是否相关
   */
  _isRelevantToGoal(goal, eventType, data) {
    // 检查条件中是否有明确的事件类型
    if (goal.conditions && goal.conditions.events) {
      const allowedEvents = Array.isArray(goal.conditions.events)
        ? goal.conditions.events
        : [goal.conditions.events]
      if (!allowedEvents.includes(eventType)) {
        return false
      }
    }
    // 检查工具名称过滤器
    if (goal.conditions && goal.conditions.toolNames) {
      const toolNames = Array.isArray(goal.conditions.toolNames)
        ? goal.conditions.toolNames
        : [goal.conditions.toolNames]
      if (data && data.toolName && !toolNames.includes(data.toolName)) {
        return false
      }
    }
    return true
  }
}

module.exports = { EventWatcher }
