/**
 * Ambient Agent 插件
 * 持续后台运行的智能代理，监控事件并主动执行操作
 */

const { Plugin } = require('../../src/core/plugin-base')
const { logger } = require('../../src/utils/logger')
const { z } = require('zod')

// 导入子模块
const { GoalState } = require('./constants')
const { StateStore } = require('./StateStore')
const { GoalManager } = require('./GoalManager')
const { EventWatcher } = require('./EventWatcher')
const { Reflector } = require('./Reflector')
const { ExplorerLoop } = require('./ExplorerLoop')

const log = logger.child('Ambient')

class AmbientAgentPlugin extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'ambient'
    this.version = '1.0.0'
    this.description = `Ambient Agent - 持续后台运行的智能代理，用于主动监控事件并执行操作

## 支持的事件类型（创建目标时 conditions.events 必须使用这些确切的名称）：
- email:received - 收到新邮件（参数：from, subject, text, messageId）
- tool:result - 工具执行完成（参数：name, args, result）
- scheduler:reminder - 定时提醒（参数：taskId, message, time）
- scheduler:task_completed - 任务完成（参数：taskId, result）
- scheduler:task_failed - 任务失败（参数：taskId, error）
- agent:message - 代理消息（参数：content, sessionId）
- think:thought_completed - 思考完成（参数：mode, topic, thought）
- webhook:received - Webhook接收（参数：headers, body, query, path）

## 在 action 参数中引用事件数据：
使用 \${event.xxx} 语法，例如：\${event.from}、\${event.subject}、\${event.text}`
    this.priority = 18
    this.system = true

    this.config = {
      enabled: config.enabled !== false,
      tickInterval: config.tickInterval || 5000,      // tick间隔（毫秒）
      cooldownPeriod: config.cooldownPeriod || 3000,  // 冷却时间（毫秒）
      persistencePath: config.persistencePath || '.agent/data/ambient',
      defaultGoals: config.defaultGoals || []
    }

    this._framework = null
    this._stateStore = null
    this._goalManager = null
    this._eventWatcher = null
    this._reflector = null
    this._explorerLoop = null
    this._memories = []
  }

  // ============================================================================
  // 生命周期
  // ============================================================================

  install(framework) {
    this._framework = framework
    this._stateStore = new StateStore(this.config.persistencePath)
    this._goalManager = new GoalManager(this._stateStore)
    this._reflector = new Reflector(this._goalManager)

    // 加载持久化的记忆
    this._memories = this._stateStore.loadMemories()

    return this
  }

  start(framework) {
    if (!this.config.enabled) {
      log.info('插件已禁用，跳过启动')
      return this
    }

    // 如果没有现有目标，创建默认目标
    if (this._goalManager.getAllGoals().length === 0 && this.config.defaultGoals.length > 0) {
      for (const goalDef of this.config.defaultGoals) {
        this._goalManager.createGoal(goalDef)
      }
    }

    // 启动事件监听器
    this._eventWatcher = new EventWatcher(this._goalManager, this._framework)
    this._eventWatcher.start()

    // 动态更新description显示支持的事件及参数
    this._updateDescription()

    // 启动探索循环
    this._explorerLoop = new ExplorerLoop(this._goalManager, this._reflector, this._framework, {
      tickInterval: this.config.tickInterval,
      cooldownPeriod: this.config.cooldownPeriod
    })
    this._explorerLoop.start()

    // 注册工具
    this._registerTools(framework)

    log.info('插件已启动')
    return this
  }

  reload(framework) {
    this._framework = framework
    if (this._explorerLoop && this._explorerLoop.isRunning()) {
      // 用新的框架引用重新启动
      this._eventWatcher = new EventWatcher(this._goalManager, this._framework)
      this._eventWatcher.start()
    }
  }

  uninstall(framework) {
    // 停止探索循环
    if (this._explorerLoop) {
      this._explorerLoop.stop()
      this._explorerLoop = null
    }

    // 停止事件监听器
    if (this._eventWatcher) {
      this._eventWatcher.stop()
      this._eventWatcher = null
    }

    // 清除引用
    this._framework = null
    this._goalManager = null
    this._reflector = null
    this._stateStore = null
    this._memories = []
  }

  // ============================================================================
  // 描述更新
  // ============================================================================

  /**
   * 动态更新插件描述，从 Framework 获取已注册的事件描述
   */
  _updateDescription() {
    if (!this._framework) return

    // 从 Framework 获取所有已注册的事件描述
    const eventDescriptions = this._framework.getEventDescriptions()

    if (eventDescriptions.size === 0) {
      // 如果没有动态注册的事件，使用默认事件列表
      const defaultEvents = [
        { type: 'tool:result', desc: '工具执行结果 - name, args, result, error' },
        { type: 'scheduler:reminder', desc: '定时提醒 - taskId, message, time' },
        { type: 'scheduler:task_completed', desc: '任务完成 - taskId, result' },
        { type: 'scheduler:task_failed', desc: '任务失败 - taskId, error' },
        { type: 'agent:message', desc: '代理消息 - content, sessionId' },
        { type: 'think:thought_completed', desc: '思考完成 - mode, topic, thought, depth' },
        { type: 'email:received', desc: '收到邮件 - from, to, subject, text, messageId, timestamp' },
        { type: 'webhook:received', desc: 'Webhook接收 - webhook, data, headers, query, path, sessionId, response' }
      ]

      const eventList = defaultEvents.map(e => `  - ${e.type} - ${e.desc}`).join('\n')
      this.description = `Ambient Agent - 持续后台运行的智能代理，用于主动监控和执行操作

## 支持的事件类型（创建目标时 conditions.events 必须使用这些确切的名称）：
${eventList}

## 在 action 参数中引用事件数据：
使用 \${event.xxx} 语法，例如：\${event.from}、\${event.subject}、\${event.text}`
      return
    }

    // 生成事件列表
    const eventList = Array.from(eventDescriptions.entries())
      .map(([type, info]) => {
        const desc = info.params || info.description || ''
        return `  - ${type} - ${desc}`
      })
      .join('\n')

    this.description = `Ambient Agent - 持续后台运行的智能代理，用于主动监控和执行操作

## 支持的事件类型（创建目标时 conditions.events 必须使用这些确切的名称）：
${eventList}

## 在 action 参数中引用事件数据：
使用 \${event.xxx} 语法，例如：\${event.from}、\${event.subject}、\${event.text}

---
💡 提示：事件描述由触发事件的插件动态注册。`
  }

  // ============================================================================
  // 工具注册
  // ============================================================================

  _registerTools(framework) {
    // ambient_goals - 列出/创建/更新/删除目标
    framework.registerTool({
      name: 'ambient_goals',
      description: '管理Ambient Agent目标 - 列出、创建、更新、删除、激活目标',
      inputSchema: z.object({
        action: z.enum(['list', 'create', 'update', 'delete', 'activate']).describe('执行的操作'),
        goalId: z.string().optional().describe('目标ID（更新/删除/激活时必需）'),
        title: z.string().optional().describe('目标标题（创建/更新时使用）'),
        description: z.string().optional().describe('目标描述（创建/更新时使用）'),
        priority: z.number().optional().describe('优先级1-10，数值越高越重要（创建/更新时使用）'),
        actions: z.array(z.object({
          id: z.string().optional().describe('操作标识符'),
          type: z.enum(['tool', 'message', 'think']).describe('操作类型'),
          name: z.string().optional().describe('工具名称（tool类型时使用）'),
          args: z.record(z.any()).optional().describe('工具参数（tool类型时使用）'),
          content: z.string().optional().describe('消息内容（message类型时使用）'),
          topic: z.string().optional().describe('思考主题（think类型时使用）'),
          mode: z.enum(['reflect', 'brainstorm', 'analyze', 'plan']).optional().describe('思考模式（think类型时使用）')
        })).optional().describe('要执行的操作列表（创建/更新时使用）'),
        conditions: z.object({
          events: z.union([z.string(), z.array(z.string())]).optional().describe('要监听的事件类型'),
          toolNames: z.union([z.string(), z.array(z.string())]).optional().describe('按工具名称过滤')
        }).optional().describe('激活条件（创建/更新时使用）')
      }),
      execute: async (args) => {
        return this._handleGoalsTool(args)
      }
    })

    // ambient_status - 获取当前循环状态
    framework.registerTool({
      name: 'ambient_status',
      description: '获取当前Ambient Agent状态 - 循环状态、进行中的目标、最近活动',
      inputSchema: z.object({}),
      execute: async () => {
        return this._handleStatusTool()
      }
    })

    // ambient_think - 触发主动LLM思考
    framework.registerTool({
      name: 'ambient_think',
      description: '为某个目标触发主动LLM思考 - 模式：reflect（反思）、brainstorm（头脑风暴）、plan（计划）、analyze（分析）',
      inputSchema: z.object({
        goalId: z.string().optional().describe('要思考的目标ID'),
        mode: z.enum(['reflect', 'brainstorm', 'plan', 'analyze']).describe('思考模式'),
        topic: z.string().optional().describe('要思考的主题'),
        depth: z.number().optional().describe('思考深度1-5')
      }),
      execute: async (args) => {
        return this._handleThinkTool(args)
      }
    })

    // ambient_remember - 存储/检索/搜索持久化记忆
    framework.registerTool({
      name: 'ambient_remember',
      description: '为Ambient Agent存储或检索持久化记忆',
      inputSchema: z.object({
        action: z.enum(['store', 'retrieve', 'search']).describe('操作：store存储记忆、retrieve检索最近、search搜索'),
        content: z.string().optional().describe('记忆内容（store时使用）'),
        key: z.string().optional().describe('记忆键（store/retrieve时使用）'),
        query: z.string().optional().describe('搜索查询（search时使用）'),
        limit: z.number().optional().describe('最大结果数（retrieve/search时使用）')
      }),
      execute: async (args) => {
        return this._handleRememberTool(args)
      }
    })

    // ambient_control - 暂停/恢复/调整探索循环
    framework.registerTool({
      name: 'ambient_control',
      description: '控制Ambient Agent探索循环 - 暂停、恢复或调整设置',
      inputSchema: z.object({
        action: z.enum(['pause', 'resume', 'status', 'adjust']).describe('控制操作'),
        tickInterval: z.number().optional().describe('新的tick间隔毫秒数（adjust时使用）'),
        cooldownPeriod: z.number().optional().describe('新的冷却时间毫秒数（adjust时使用）')
      }),
      execute: async (args) => {
        return this._handleControlTool(args)
      }
    })
  }

  // ============================================================================
  // 工具处理器
  // ============================================================================

  _handleGoalsTool(args) {
    const { action, goalId, title, description, priority, actions, conditions } = args

    switch (action) {
      case 'list': {
        const allGoals = this._goalManager.getAllGoals()
        return {
          success: true,
          goals: allGoals.map(g => ({
            id: g.id,
            title: g.title,
            state: g.state,
            priority: g.priority,
            actionsCount: g.actions ? g.actions.length : 0,
            attempts: g.attempts,
            createdAt: g.createdAt,
            activatedAt: g.activatedAt,
            completedAt: g.completedAt,
            failedAt: g.failedAt
          })),
          total: allGoals.length,
          active: this._goalManager.getActiveGoals().length,
          pending: this._goalManager.getPendingGoals().length
        }
      }

      case 'create': {
        if (!title) {
          return { success: false, error: '创建目标需要提供标题' }
        }
        const goal = this._goalManager.createGoal({ title, description, priority, actions, conditions })
        return { success: true, goal }
      }

      case 'update': {
        if (!goalId) {
          return { success: false, error: '更新目标需要提供目标ID' }
        }
        const updates = {}
        if (title !== undefined) updates.title = title
        if (description !== undefined) updates.description = description
        if (priority !== undefined) updates.priority = priority
        if (actions !== undefined) updates.actions = actions
        if (conditions !== undefined) updates.conditions = conditions
        const goal = this._goalManager.updateGoal(goalId, updates)
        return goal ? { success: true, goal } : { success: false, error: '目标未找到' }
      }

      case 'delete': {
        if (!goalId) {
          return { success: false, error: '删除目标需要提供目标ID' }
        }
        const deleted = this._goalManager.deleteGoal(goalId)
        return { success: deleted }
      }

      case 'activate': {
        if (!goalId) {
          return { success: false, error: '激活目标需要提供目标ID' }
        }
        const goal = this._goalManager.activateGoal(goalId)
        return goal ? { success: true, goal } : { success: false, error: '目标未找到或不是待激活状态' }
      }

      default:
        return { success: false, error: `未知操作: ${action}` }
    }
  }

  _handleStatusTool() {
    if (!this._explorerLoop) {
      return { success: false, error: '探索循环未初始化' }
    }

    const loopStatus = this._explorerLoop.getStatus()
    const activeGoals = this._goalManager.getActiveGoals().map(g => ({
      id: g.id,
      title: g.title,
      priority: g.priority,
      attempts: g.attempts,
      lastActionId: g.lastActionId
    }))
    const pendingGoals = this._goalManager.getPendingGoals().map(g => ({
      id: g.id,
      title: g.title,
      priority: g.priority
    }))

    return {
      success: true,
      loop: {
        running: loopStatus.running,
        tickCount: loopStatus.tickCount,
        lastTick: loopStatus.lastTick,
        tickInterval: this.config.tickInterval,
        cooldownPeriod: this.config.cooldownPeriod
      },
      activeGoals,
      pendingGoals,
      recentActivities: loopStatus.recentActivities
    }
  }

  async _handleThinkTool(args) {
    const { goalId, mode, topic, depth } = args

    // 获取活跃代理
    const agent = this._getActiveAgent()
    if (!agent) {
      return { success: false, error: '没有可用的活跃代理' }
    }

    // 构建思考提示
    let prompt = ''
    if (goalId) {
      const goal = this._goalManager.getGoal(goalId)
      if (goal) {
        const { ThinkModePrompts } = require('./constants')
        const modePrompts = ThinkModePrompts
        const modePromptFn = modePrompts[mode]
        prompt = modePromptFn ? modePromptFn(goal, topic) : modePrompts.reflect(goal, topic)
      } else {
        return { success: false, error: '目标未找到' }
      }
    } else {
      const { FreeThinkPrompts } = require('./constants')
      const modePrompts = FreeThinkPrompts
      const modePromptFn = modePrompts[mode]
      prompt = modePromptFn ? modePromptFn(topic) : modePrompts.reflect(topic)
    }

    // 如果代理忙，等待其变为可用
    let attempts = 0
    const maxWaitAttempts = 10
    const waitInterval = 500

    while (agent._status === 'busy' && attempts < maxWaitAttempts) {
      log.info('代理忙，等待中...')
      await new Promise(resolve => setTimeout(resolve, waitInterval))
      attempts++
    }

    if (agent._status === 'busy') {
      return {
        success: false,
        error: '代理繁忙，无法及时变为可用。请稍后重试。',
        queued: true
      }
    }

    // 通过代理执行思考
    const thinkPlugin = this._framework.pluginManager.get('think')
    if (thinkPlugin) {
      const result = await thinkPlugin._triggerThinking({ topic: prompt, mode, depth: depth || 2 })
      // 如果结果提示繁忙，返回更友好的消息
      if (result && result.message && result.message.includes && result.message.includes('busy')) {
        return {
          success: true,
          queued: true,
          message: '思考请求已排队，将在代理空闲时处理。'
        }
      }
      return result
    }

    // 备用：直接推送消息
    return agent.pushMessage(prompt).then(result => ({
      success: true,
      result: typeof result === 'string' ? result : JSON.stringify(result)
    })).catch(err => ({
      success: false,
      error: err.message
    }))
  }

  _handleRememberTool(args) {
    const { action, content, key, query, limit } = args
    const maxResults = limit || 10

    switch (action) {
      case 'store': {
        if (!content) {
          return { success: false, error: '存储需要提供内容' }
        }
        const memoryKey = key || `memory_${Date.now()}`
        const memory = {
          key: memoryKey,
          content,
          timestamp: new Date()
        }
        this._memories.push(memory)
        this._stateStore.saveMemories(this._memories)
        return { success: true, memory }
      }

      case 'retrieve': {
        const memories = this._memories.slice(-maxResults).reverse()
        return {
          success: true,
          memories,
          total: this._memories.length
        }
      }

      case 'search': {
        if (!query) {
          return { success: false, error: '搜索需要提供查询词' }
        }
        const queryLower = query.toLowerCase()
        const results = this._memories
          .filter(m => m.content.toLowerCase().includes(queryLower))
          .slice(-maxResults)
          .reverse()
        return {
          success: true,
          results,
          total: results.length
        }
      }

      default:
        return { success: false, error: `未知操作: ${action}` }
    }
  }

  _handleControlTool(args) {
    const { action, tickInterval, cooldownPeriod } = args

    switch (action) {
      case 'pause': {
        if (!this._explorerLoop) {
          return { success: false, error: '探索循环未初始化' }
        }
        this._explorerLoop.pause()
        return { success: true, message: '探索循环已暂停' }
      }

      case 'resume': {
        if (!this._explorerLoop) {
          return { success: false, error: '探索循环未初始化' }
        }
        this._explorerLoop.resume()
        return { success: true, message: '探索循环已恢复' }
      }

      case 'status': {
        if (!this._explorerLoop) {
          return { success: false, error: '探索循环未初始化' }
        }
        const status = this._explorerLoop.getStatus()
        return {
          success: true,
          running: status.running,
          tickCount: status.tickCount,
          lastTick: status.lastTick,
          tickInterval: this.config.tickInterval,
          cooldownPeriod: this.config.cooldownPeriod
        }
      }

      case 'adjust': {
        if (tickInterval) {
          this.config.tickInterval = tickInterval
        }
        if (cooldownPeriod) {
          this.config.cooldownPeriod = cooldownPeriod
        }
        return {
          success: true,
          message: '设置已调整',
          tickInterval: this.config.tickInterval,
          cooldownPeriod: this.config.cooldownPeriod
        }
      }

      default:
        return { success: false, error: `未知操作: ${action}` }
    }
  }

  _getActiveAgent() {
    if (this._framework._mainAgent) {
      return this._framework._mainAgent
    }
    const agents = this._framework._agents || []
    return agents.length > 0 ? agents[agents.length - 1] : null
  }
}

module.exports = AmbientAgentPlugin
