/**
 * GoalManager - 管理目标及其生命周期状态
 */

const { logger } = require('../../src/utils/logger')
const { GoalState } = require('./constants')
const { generateId } = require('../../src/utils/id')

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

class GoalManager {
  constructor(stateStore) {
    this._goals = new Map()
    this._stateStore = stateStore
    this._loadGoals()
  }

  _loadGoals() {
    const savedGoals = this._stateStore.loadGoals()
    for (const goal of savedGoals) {
      this._goals.set(goal.id, goal)
    }
  }

  _persist() {
    const goalsArray = Array.from(this._goals.values())
    this._stateStore.saveGoals(goalsArray)
  }

  /**
   * 创建新目标
   * @param {Object} goalData - 目标数据
   * @returns {Object} 创建的目标
   */
  createGoal(goalData) {
    const actions = goalData.actions || []
    const goal = {
      id: generateId(),
      title: goalData.title || '未命名目标',
      description: goalData.description || '',
      priority: goalData.priority || 5,
      state: GoalState.PENDING,
      actions: actions,
      _originalActions: actions.slice(),  // 保存原始 actions，用于事件驱动目标重置
      conditions: goalData.conditions || {},
      createdAt: new Date(),
      updatedAt: new Date(),
      activatedAt: null,
      completedAt: null,
      failedAt: null,
      attempts: 0,
      maxAttempts: goalData.maxAttempts || 10,
      consecutiveSameActions: 0,
      lastActionId: null,
      eventsReceived: []
    }
    this._goals.set(goal.id, goal)
    this._persist()
    return goal
  }

  /**
   * 获取目标
   * @param {string} id - 目标ID
   * @returns {Object|null} 目标对象
   */
  getGoal(id) {
    return this._goals.get(id)
  }

  /**
   * 获取所有目标
   * @returns {Array} 所有目标数组
   */
  getAllGoals() {
    return Array.from(this._goals.values())
  }

  /**
   * 获取活跃目标
   * @returns {Array} 活跃目标数组
   */
  getActiveGoals() {
    return Array.from(this._goals.values()).filter(g => g.state === GoalState.ACTIVE)
  }

  /**
   * 获取待处理目标
   * @returns {Array} 待处理目标数组
   */
  getPendingGoals() {
    return Array.from(this._goals.values()).filter(g => g.state === GoalState.PENDING)
  }

  /**
   * 更新目标
   * @param {string} id - 目标ID
   * @param {Object} updates - 更新数据
   * @returns {Object|null} 更新后的目标
   */
  updateGoal(id, updates) {
    const goal = this._goals.get(id)
    if (!goal) return null
    Object.assign(goal, updates, { updatedAt: new Date() })
    this._persist()
    return goal
  }

  /**
   * 激活目标
   * @param {string} id - 目标ID
   * @returns {Object|null} 激活后的目标
   */
  activateGoal(id) {
    const goal = this._goals.get(id)
    if (!goal || goal.state !== GoalState.PENDING) return null
    goal.state = GoalState.ACTIVE
    goal.activatedAt = new Date()
    goal.updatedAt = new Date()
    this._persist()
    return goal
  }

  /**
   * 标记目标为已完成
   * @param {string} id - 目标ID
   * @returns {Object|null} 目标对象
   */
  completeGoal(id) {
    const goal = this._goals.get(id)
    if (!goal) return null
    goal.state = GoalState.COMPLETED
    goal.completedAt = new Date()
    goal.updatedAt = new Date()
    this._persist()
    return goal
  }

  /**
   * 标记目标为失败
   * @param {string} id - 目标ID
   * @param {string} reason - 失败原因
   * @returns {Object|null} 目标对象
   */
  failGoal(id, reason) {
    const goal = this._goals.get(id)
    if (!goal) return null
    goal.state = GoalState.FAILED
    goal.failedAt = new Date()
    goal.failureReason = reason
    goal.updatedAt = new Date()
    this._persist()
    return goal
  }

  /**
   * 删除目标
   * @param {string} id - 目标ID
   * @returns {boolean} 是否删除成功
   */
  deleteGoal(id) {
    const deleted = this._goals.delete(id)
    if (deleted) this._persist()
    return deleted
  }

  /**
   * 向目标添加事件（带去重）
   * @param {string} goalId - 目标ID
   * @param {Object} event - 事件数据
   */
  addEventToGoal(goalId, event) {
    const goal = this._goals.get(goalId)
    if (!goal) return

    // 通用去重：如果最近 2 秒内已有相同类型的事件，跳过
    const now = Date.now()
    const recentSameEvent = goal.eventsReceived.find(e =>
      e.event === event.type && (now - new Date(e.timestamp).getTime()) < 2000
    )
    if (recentSameEvent) {
      log.info(`跳过重复事件: ${event.type} (2秒内不重复添加)`)
      return
    }

    // event 格式: { type: 'email:received', email: {...}, timestamp: ... }
    // 需要提取 type 和 data（email 对象）
    goal.eventsReceived.push({
      event: event.type,
      data: event.data || event.email || event,
      timestamp: new Date()
    })
    this._persist()
  }
}

module.exports = { GoalManager }
