/**
 * 工具插件
 * 提供内置工具和热重载功能
 */

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

class ToolsPlugin extends Plugin {
  constructor(config = {}) {
    super()
    this.name = 'tools'
    this.version = '1.0.0'
    this.description = '内置工具插件，提供热重载和工具管理功能'
    this.priority = 10
    
    this.system = true 

    this._framework = null
  }

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

  start(framework) {
    // 工具已通过 install 注册
  }

  _registerBuiltinTools() {
    const framework = this._framework

    // 热重载插件工具
    framework.registerTool({
      name: 'reload_plugins',
      description: '热重载插件。可以重载单个指定插件，或重载所有插件。',
      inputSchema: z.object({
        pluginName: z.string().optional().describe('可选：指定要重载的插件名称，不指定则重载所有插件')
      }),
      execute: async (args) => {
        try {
          if (args.pluginName) {
            await framework.reloadPlugin(args.pluginName)
            return {
              success: true,
              message: `Plugin '${args.pluginName}' reloaded successfully`
            }
          } else {
            await framework.reloadAllPlugins()
            return {
              success: true,
              message: 'All plugins reloaded successfully'
            }
          }
        } catch (err) {
          return {
            success: false,
            error: err.message
          }
        }
      }
    })

    // 列出所有插件工具（包括未加载的）
    framework.registerTool({
      name: 'list_plugins',
      description: '列出所有插件（包括未加载的）',
      inputSchema: z.object({}),
      execute: async () => {
        const plugins = framework.pluginManager.getAllKnown()
        return {
          success: true,
          plugins: plugins.map(p => ({
            name: p.name,
            status: p.status,
            enabled: p.enabled,
            version: p.version,
            system: p.system
          }))
        }
      }
    })

    // 启用插件工具
    framework.registerTool({
      name: 'enable_plugin',
      description: '启用指定插件',
      inputSchema: z.object({
        name: z.string().describe('插件名称')
      }),
      execute: async (args) => {
        try {
          await framework.enablePlugin(args.name)
          return { success: true, message: `插件 '${args.name}' 已启用` }
        } catch (err) {
          return { success: false, error: err.message }
        }
      }
    })

    // 禁用插件工具
    framework.registerTool({
      name: 'disable_plugin',
      description: '禁用指定插件',
      inputSchema: z.object({
        name: z.string().describe('插件名称')
      }),
      execute: async (args) => {
        try {
          await framework.disablePlugin(args.name)
          return { success: true, message: `插件 '${args.name}' 已禁用` }
        } catch (err) {
          return { success: false, error: err.message }
        }
      }
    })

    // 获取工具列表
    framework.registerTool({
      name: 'list_tools',
      description: '列出所有已注册的工具',
      inputSchema: z.object({}),
      execute: async () => {
        const tools = framework.getTools()
        return {
          success: true,
          tools: tools.map(t => ({
            name: t.name,
            description: t.description
          }))
        }
      }
    })

    // 获取插件配置
    framework.registerTool({
      name: 'get_plugin_config',
      description: '获取指定插件的当前配置',
      inputSchema: z.object({
        name: z.string().describe('插件名称')
      }),
      execute: async (args) => {
        const plugin = framework.pluginManager.get(args.name)
        if (!plugin) {
          return { success: false, error: `Plugin '${args.name}' not found` }
        }
        return {
          success: true,
          config: plugin.config || {}
        }
      }
    })

    // 更新插件配置
    framework.registerTool({
      name: 'update_plugin_config',
      description: '更新指定插件的配置，会合并到现有配置并持久化保存',
      inputSchema: z.object({
        name: z.string().describe('插件名称'),
        config: z.record(z.any()).describe('要更新的配置（会合并到现有配置）')
      }),
      execute: async (args) => {
        try {
          const newConfig = framework.updatePluginConfig(args.name, args.config)
          return { success: true, message: `插件 '${args.name}' 配置已更新`, config: newConfig }
        } catch (err) {
          return { success: false, error: err.message }
        }
      }
    })
  }

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

  uninstall(framework) {
    // 注销内置工具
    framework.toolRegistry.unregister('reload_plugins')
    framework.toolRegistry.unregister('list_plugins')
    framework.toolRegistry.unregister('list_tools')
    framework.toolRegistry.unregister('enable_plugin')
    framework.toolRegistry.unregister('disable_plugin')
    framework.toolRegistry.unregister('get_plugin_config')
    framework.toolRegistry.unregister('update_plugin_config')
    this._framework = null
  }
}

module.exports = ToolsPlugin
