/**
 * 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:call', (data) => this._handleEvent('tool:call', data)],
      ['tool:result', (data) => this._handleEvent('tool:result', data)],
      ['tool:error', (data) => this._handleEvent('tool:error', data)],
      // Scheduler 事件
      ['scheduler:task_created', (data) => this._handleEvent('scheduler:task_created', data)],
      ['scheduler:reminder', (data) => this._handleEvent('scheduler:reminder', data)],
      ['scheduler:task_completed', (data) => this._handleEvent('scheduler:task_completed', data)],
      ['scheduler:task_failed', (data) => this._handleEvent('scheduler:task_failed', data)],
      // Agent/Think 事件
      ['agent:message', (data) => this._handleEvent('agent:message', data)],
      ['think:thought_completed', (data) => this._handleEvent('think:thought_completed', data)],
      // Email/Webhook 事件
      ['email:received', (data) => this._handleEvent('email:received', data)],
      ['webhook:received', (data) => this._handleEvent('webhook:received', data)],
      ['webhook:processed', (data) => this._handleEvent('webhook:processed', data)],
      // Worker/Subagent 事件
      ['worker:completed', (data) => this._handleEvent('worker:completed', data)],
      ['worker:error', (data) => this._handleEvent('worker:error', data)],
      ['subagent:chat:end', (data) => this._handleEvent('subagent:chat:end', 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()

    for (const goal of activeGoals) {
      if (this._isRelevantToGoal(goal, type, data)) {
        // 直接传入原样数据
        this._goalManager.addEventToGoal(goal.id, { eventType: type, data })
      }
    }

    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, { eventType: type, data })
      }
    }
  }

  /**
   * 检查事件是否与目标相关
   */
  _isRelevantToGoal(goal, eventType, data) {
    // 检查事件类型
    if (goal.conditions?.events) {
      const allowed = Array.isArray(goal.conditions.events) ? goal.conditions.events : [goal.conditions.events]
      if (!allowed.includes(eventType)) return false
    }
    // 检查工具名称
    if (goal.conditions?.toolNames) {
      const toolNames = Array.isArray(goal.conditions.toolNames) ? goal.conditions.toolNames : [goal.conditions.toolNames]
      const eventName = data?.toolName || data?.name
      if (!eventName) return true
      // 统一下划线和冒号格式进行匹配
      const normalize = (n) => n?.replace(/_/g, ':')
      const normName = normalize(eventName)
      const isMatch = toolNames.some(tn => normalize(tn) === normName || tn === eventName)
      if (!isMatch) return false
    }
    return true
  }
}

module.exports = { EventWatcher }
