import { Injectable } from '@nestjs/common';
import { KnowledgeQaService } from '@modules/knowledge-base/services/knowledge-qa.service';
import type { AgentTool, ToolDescriptor, ToolInvocation, ToolResult } from './tool.types';

/**
 * `knowledge_query` tool —— PR6 真后端接入。
 *
 * 走 KnowledgeBase 模块 `KnowledgeQaService.ask(question, userId)` —— 真 RAGFlow 索引。
 * 不再是 PR5 关键字硬编码。
 */
@Injectable()
export class KnowledgeQueryTool implements AgentTool {
  constructor(private readonly qaService: KnowledgeQaService) {}

  readonly descriptor: ToolDescriptor = {
    name: 'knowledge_query',
    description:
      '查询**本公司内部**知识库（RAGFlow 真索引）—— 仅限：公司内部制度、HR 流程、' +
      'IT 操作手册、SOP、入职指南、内部 FAQ 等。' +
      '**不要用于查询任何外部公司 / 公开信息 / 新闻 / 实时数据**——那种走 web_search。',
    inputSchema: {
      question: { type: 'string', required: true, description: '关于公司内部的问题或关键词' },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams'] },
  };

  async invoke(inv: ToolInvocation): Promise<ToolResult> {
    const q = String(inv.input.question ?? '').trim();
    if (!q) return { ok: false, errorMessage: 'question 不能为空' };

    try {
      const result = await this.qaService.ask(q, inv.userId);
      return {
        ok: true,
        output: {
          answer: result.answer,
          confidence: result.confidence,
          sources: result.sources,
          metadata: result.metadata,
        },
      };
    } catch (err) {
      return {
        ok: false,
        errorMessage: `知识库查询失败：${(err as Error).message}（RAGFlow 后端不可达时此工具不可用）`,
      };
    }
  }
}
