/**
 * `SendMessage` tool —— 父 agent 给 sub-agent 继续发消息（多 Agent 间通信）。
 *
 * 设计：delegate_task 拿到 childSessionId 后，父 agent 想继续指挥子 agent
 * （"再总结一遍"、"加一个观点"、"用更口语的语气"），调 SendMessage 即可。
 *
 * 行为：在指定 sessionId 上跑一轮 runTurn，prompt 当 user message，返回子 agent
 * 的 ASSISTANT_TEXT。本质上等于"在另一个 session 上发一次对话"，但通过 LLM
 * 工具协议显式化，让 ToolRegistry / 审计层能追踪"父在 t1 调 SendMessage 到 child A"。
 *
 * 安全：跨 org 调用被 messages.runTurn 内部 assertSessionOwnership 拦截。
 */

import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { AgentMessagesService } from '../services/messages.service';
import type { AgentTool, ToolDescriptor, ToolInvocation, ToolResult } from './tool.types';

@Injectable()
export class SendMessageTool implements AgentTool {
  constructor(
    @Inject(forwardRef(() => AgentMessagesService))
    private readonly messagesService: AgentMessagesService,
  ) {}

  readonly descriptor: ToolDescriptor = {
    name: 'SendMessage',
    description:
      '给**另一个 session**（通常是 sub-agent）发一条 user prompt 并等它回复。' +
      '典型用例：delegate_task 拿到 childSessionId 后，父 agent 想让子 agent "再调整一下" → SendMessage(childSessionId, prompt)。' +
      '不要用 SendMessage 给当前 session 自己发（用普通回复即可）。',
    inputSchema: {
      // 用 targetSessionId 避开 controller 的 sessionId merge override（详见 controller 91 行）
      targetSessionId: { type: 'string', required: true, description: '目标 session id（通常是 delegate_task 返回的 childSessionId）' },
      prompt: { type: 'string', required: true, description: '要发的消息内容' },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams', 'cli'] },
    writeAction: true,
  };

  async invoke(inv: ToolInvocation): Promise<ToolResult> {
    const targetSessionId = String(inv.input.targetSessionId ?? '').trim();
    const prompt = String(inv.input.prompt ?? '').trim();
    if (!targetSessionId) return { ok: false, errorMessage: 'targetSessionId 不能为空' };
    if (!prompt) return { ok: false, errorMessage: 'prompt 不能为空' };
    if (targetSessionId === inv.sessionId) {
      return { ok: false, errorMessage: '不能给当前 session 自己发；用普通回复' };
    }
    try {
      const result = await this.messagesService.runTurn({
        sessionId: targetSessionId,
        organizationId: inv.organizationId,
        userId: inv.userId,
        prompt,
      });
      const assistantMsg = result.messages.find((m) => m.type === 'ASSISTANT_TEXT');
      return {
        ok: true,
        output: {
          targetSessionId,
          turnId: result.turnId,
          reply: assistantMsg?.content ?? '(目标 session 没产出文本回复)',
        },
      };
    } catch (err) {
      return { ok: false, errorMessage: (err as Error).message };
    }
  }
}
