/**
 * 子任务委派工具
 *
 * 允许主 Agent 将子任务委派给独立的 SubAgent 执行。
 * SubAgent 运行在独立的 AgentLoopEngine 实例中，可限制可用工具。
 *
 * @see electron/harness/orchestration/orchestrator.ts — TaskOrchestrator
 */

import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
import type { MetonaToolDef } from '../../../harness/types';
import { MetonaToolCategory, MetonaRiskLevel } from '../../../harness/types';
import type { TaskOrchestrator } from '../../orchestration/orchestrator';

export class DelegateTaskTool implements IMetonaTool {
  readonly definition: MetonaToolDef = {
    name: 'delegate_task',
    description: 'Delegate a sub-task to an independent SubAgent for parallel or isolated execution. The SubAgent runs its own ReAct loop and returns the final result. Use this for complex sub-tasks that benefit from focused reasoning.',
    parameters: {
      type: 'object',
      properties: {
        description: {
          type: 'string',
          description: 'Clear and detailed description of the sub-task to delegate. This will be the SubAgent\'s user message.',
        },
        tools: {
          type: 'array',
          items: { type: 'string', description: 'Tool name' },
          description: 'Optional whitelist of tool names the SubAgent can use (e.g. ["read_file", "web_search"]). If omitted, SubAgent inherits all tools.',
        },
        maxIterations: {
          type: 'number',
          description: 'Maximum iterations for the SubAgent (default: 10)',
        },
      },
      required: ['description'],
    },
    category: MetonaToolCategory.CUSTOM,
    riskLevel: MetonaRiskLevel.MEDIUM,
    requiresPermission: false,
    timeoutMs: 300_000, // 5 分钟，子任务可能较复杂
  };

  constructor(private orchestrator: TaskOrchestrator) {}

  async execute(args: Record<string, unknown>, context: ToolExecutionContext): Promise<unknown> {
    const description = args.description as string;
    const tools = args.tools as string[] | undefined;
    const maxIterations = (args.maxIterations as number) ?? 10;

    if (!description) {
      return { success: false, error: 'Missing required parameter: description' };
    }

    try {
      const result = await this.orchestrator.delegate({
        description,
        parentSessionId: context.sessionId,
        maxIterations,
        tools,
      });

      return {
        success: result.success,
        result: result.result,
        durationMs: result.durationMs,
        taskId: result.taskId,
        iterations: result.iterations,
      };
    } catch (error) {
      return {
        success: false,
        error: `SubAgent execution failed: ${(error as Error).message}`,
      };
    }
  }
}
