/**
 * Coordinator Plugin
 * 提供Coordinator模式的工具集：
 * - spawn_worker: 创建Worker
 * - send_message_to_worker: 继续Worker
 * - stop_worker: 停止Worker
 * - list_workers: 列出Worker
 */

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

const log = logger.child('CoordinatorPlugin');

class CoordinatorPlugin extends Plugin {
  constructor(config = {}) {
    super();
    this.name = 'coordinator';
    this.version = '1.0.0';
    this.description = 'Coordinator模式插件，支持多Worker协作';
    this.priority = 50;

    this._framework = null;
    this._coordinatorAgent = null;
  }

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

  start(framework) {
    this._framework = framework;

    // 初始化CoordinatorManager（如果尚未初始化）
    if (!framework._coordinatorManager) {
      // framework.initCoordinatorManager 会创建并设置
    }

    // 获取主Agent作为默认的Coordinator
    const mainAgent = framework._mainAgent;
    if (mainAgent) {
      // 初始化CoordinatorManager并传入coordinatorAgent
      framework.initCoordinatorManager(mainAgent);

      // 注册Coordinator工具到主Agent
      this.registerTools(mainAgent);

      // 注册系统提示词部分，让Agent知道如何使用Coordinator模式
      this._registerCoordinatorPrompt(mainAgent);

      // 监听Worker事件用于生成通知
      this._setupWorkerEventListeners(framework);

      log.debug(' Coordinator plugin initialized with main agent');
    }

    return this;
  }

  /**
   * 注册Coordinator模式提示词到Agent
   * @private
   */
  _registerCoordinatorPrompt(agent) {
    if (!agent || typeof agent.registerPromptPart !== 'function') {
      return;
    }

    agent.registerPromptPart('coordinator-mode', 650, () => `
【并行任务处理 - Coordinator 模式】
当遇到可并行处理的任务时（如多主题搜索、多文件处理、多计算任务），使用以下工具：

- spawn_worker: 创建独立Worker并行执行任务
- send_message_to_worker: 向Worker发送消息继续执行
- stop_worker: 停止Worker
- list_workers: 查看所有Worker状态
- get_worker: 查看单个Worker详情

【使用场景】
- "帮我搜索X、Y、Z" → 使用 spawn_worker 并行执行
- "帮我同时处理这几个文件" → 使用 spawn_worker 并行执行
- 需要主动查询Worker结果时 → 使用 get_worker / list_workers

【重要】
- spawn_worker 创建后立即返回，Worker在后台执行
- 可同时创建多个Worker并行处理不同任务
- Worker完成后生成 <task-notification> JSON 通知
`);
  }

  /**
   * 设置Worker事件监听器
   * @private
   */
  _setupWorkerEventListeners(framework) {
    const coordinatorManager = framework.getCoordinatorManager();
    if (!coordinatorManager) return;

    // 监听Worker完成事件
    coordinatorManager.on('worker:completed', (data) => {
      // 通知会被发送到Coordinator Agent的事件队列
      framework.emit('coordinator:worker-completed', data);
    });

    // 监听Worker错误事件
    coordinatorManager.on('worker:error', (data) => {
      framework.emit('coordinator:worker-error', data);
    });

    // 监听Worker停止事件
    coordinatorManager.on('worker:stopped', (data) => {
      framework.emit('coordinator:worker-stopped', data);
    });
  }

  /**
   * 设置Coordinator Agent
   * @param {Agent} agent - Coordinator Agent实例
   */
  setCoordinatorAgent(agent) {
    this._coordinatorAgent = agent;
  }

  /**
   * 注册Coordinator工具到指定Agent
   * @param {Agent} agent - Agent实例
   */
  registerTools(agent) {
    // spawn_worker - 创建Worker
    agent.registerTool({
      name: 'spawn_worker',
      description: '创建一个独立的Worker Agent来执行任务。Worker会在后台异步执行，完成后通过事件通知。',
      inputSchema: z.object({
        worker_name: z.string().describe('Worker的唯一名称'),
        task: z.string().describe('给Worker的初始任务描述'),
        system_prompt: z.string().optional().describe('可选的系统提示词'),
        tools: z.array(z.string()).optional().describe('Worker可用的工具名称列表'),
      }),
      execute: async (args, fw) => {
        const coordinatorManager = fw.getCoordinatorManager();
        if (!coordinatorManager) {
          return { success: false, error: 'CoordinatorManager not initialized' };
        }

        try {
          const result = await coordinatorManager.createWorker({
            name: args.worker_name,
            task: args.task,
            systemPrompt: args.system_prompt,
            tools: args.tools,
          });

          return {
            success: true,
            workerId: result.workerId,
            status: result.status,
            message: `Worker '${args.worker_name}' created and running`,
          };
        } catch (err) {
          return { success: false, error: err.message };
        }
      },
    });

    // send_message_to_worker - 继续Worker
    agent.registerTool({
      name: 'send_message_to_worker',
      description: '向指定的Worker发送消息，继续其执行',
      inputSchema: z.object({
        worker_name: z.string().describe('Worker名称'),
        message: z.string().describe('要发送给Worker的消息'),
      }),
      execute: async (args, fw) => {
        const coordinatorManager = fw.getCoordinatorManager();
        if (!coordinatorManager) {
          return { success: false, error: 'CoordinatorManager not initialized' };
        }

        try {
          const result = await coordinatorManager.sendToWorker(args.worker_name, args.message);
          return {
            success: true,
            workerName: args.worker_name,
            result: result.message || result,
          };
        } catch (err) {
          return { success: false, error: err.message };
        }
      },
    });

    // stop_worker - 停止Worker
    agent.registerTool({
      name: 'stop_worker',
      description: '停止指定的Worker',
      inputSchema: z.object({
        worker_name: z.string().describe('Worker名称'),
        reason: z.string().optional().describe('停止原因'),
      }),
      execute: async (args, fw) => {
        const coordinatorManager = fw.getCoordinatorManager();
        if (!coordinatorManager) {
          return { success: false, error: 'CoordinatorManager not initialized' };
        }

        try {
          const result = coordinatorManager.stopWorker(args.worker_name, args.reason);
          return {
            success: true,
            ...result,
          };
        } catch (err) {
          return { success: false, error: err.message };
        }
      },
    });

    // list_workers - 列出Worker
    agent.registerTool({
      name: 'list_workers',
      description: '列出所有活跃的Worker',
      inputSchema: z.object({}),
      execute: async (args, fw) => {
        const coordinatorManager = fw.getCoordinatorManager();
        if (!coordinatorManager) {
          return { success: false, error: 'CoordinatorManager not initialized' };
        }

        const workers = coordinatorManager.listWorkers();
        return {
          success: true,
          count: workers.length,
          workers,
        };
      },
    });

    // get_worker - 获取Worker详情
    agent.registerTool({
      name: 'get_worker',
      description: '获取指定Worker的详细信息',
      inputSchema: z.object({
        worker_name: z.string().describe('Worker名称'),
      }),
      execute: async (args, fw) => {
        const coordinatorManager = fw.getCoordinatorManager();
        if (!coordinatorManager) {
          return { success: false, error: 'CoordinatorManager not initialized' };
        }

        const worker = coordinatorManager.getWorker(args.worker_name);
        if (!worker) {
          return { success: false, error: `Worker '${args.worker_name}' not found` };
        }

        return {
          success: true,
          worker,
        };
      },
    });

    log.debug(' Coordinator tools registered');
  }

  reload(framework) {
    this._framework = framework;
  }

  uninstall(framework) {
    const coordinatorManager = framework.getCoordinatorManager();
    if (coordinatorManager) {
      coordinatorManager.destroy();
    }
    this._framework = null;
    this._coordinatorAgent = null;
  }
}

module.exports = { CoordinatorPlugin };
