/**
 * AI 插件
 * 提供 AI 对话能力
 */

const { Plugin } = require('../src/core/plugin-base')
const { logger } = require('../src/utils/logger')
const log = logger.child('AIPlugin')
const { createAI } = require('../src/core/provider')

class AIPlugin extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'ai'
    this.version = '1.0.0'
    this.description = 'AI 对话能力插件'
    this.priority = 1  // 最先加载
    this.system = true 

    this.config = {
      provider: config.provider || 'deepseek',
      model: config.model || 'deepseek-chat',
      apiKey: config.apiKey,
      baseURL: config.baseURL,
      maxSteps: config.maxSteps || 20,
      maxOutputTokens:config.maxOutputTokens||parseInt(process.env.MAX_OUTPUT_TOKENS)||8192
    }

    this._aiClient = null
    this._framework = null
  }

  install(framework) {
    this._framework = framework
    this._initAIClient()
    return this
  }

  start(framework) {
    // AI client 已在 install 中初始化
    return this
  }

  _initAIClient() {

    if (!this.config.apiKey) {
      log.warn(' No API key provided, AI features disabled')
      return
    }
    try {
      const provider = createAI({
        provider: this.config.provider,
        model: this.config.model,
        apiKey: this.config.apiKey,
        baseURL: this.config.baseURL
      })

      // 创建模型实例
      this._aiClient = provider(this.config.model)
      log.info(` Initialized ${this.config.provider}/${this.config.model}`)
    } catch (err) {
      log.error(' Failed to initialize AI client:', err.message)
    }
  }

  /**
   * 获取 AI 客户端
   * @returns {Object} AI 模型客户端
   */
  getAIClient() {
    return this._aiClient
  }

  /**
   * 获取配置
   * @returns {Object}
   */
  getConfig() {
    return { ...this.config }
  }

  reload(framework) {
    log.info(' Reloading...')
    this._framework = framework
    this._initAIClient()

    // 刷新所有已有 Agent 的 AI client
    for (const agent of framework._agents || []) {
      if (agent._chatHandler) {
        agent._chatHandler.setAIClient(this._aiClient)
        log.info(` Refreshed AI client for agent: ${agent.name}`)
      }
    }
  }

  uninstall(framework) {
    this._aiClient = null
    this._framework = null
  }
}

module.exports = AIPlugin
