/**
 * `web_search` tool —— 外部公开信息搜索。
 *
 * 跟 knowledge_query 互补：
 *   - knowledge_query：仅本公司内部（制度/流程/操作手册）
 *   - web_search：外部世界（公开新闻、第三方公司、新模型发布、实时信息）
 *
 * Provider 由 WebSearchService 内部 auto-detect（Tavily > DuckDuckGo HTML 兜底）。
 */

import { Injectable } from '@nestjs/common';
import { WebSearchService } from '../services/web-search.service';
import type { AgentTool, ToolDescriptor, ToolInvocation, ToolResult } from './tool.types';

@Injectable()
export class WebSearchTool implements AgentTool {
  constructor(private readonly webSearch: WebSearchService) {}

  readonly descriptor: ToolDescriptor = {
    name: 'web_search',
    description:
      '搜索**互联网公开信息**（外部公司、新闻、第三方资讯、实时事件、技术文档等）。' +
      '需要时不要犹豫，凡是涉及外部世界 / 我们公司之外的事都用本工具，不要用 knowledge_query。' +
      '不可用于查询本公司内部制度 / 项目 / 审批数据。',
    inputSchema: {
      query: {
        type: 'string',
        required: true,
        description: '搜索关键词或短语（中英文均可），尽量具体——如 "Freddie Future 2026 融资"',
      },
      limit: {
        type: 'number',
        description: '返回结果数，默认 5，上限 10',
      },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams', 'cli'] },
  };

  async invoke(inv: ToolInvocation): Promise<ToolResult> {
    const query = String(inv.input.query ?? '').trim();
    if (!query) return { ok: false, errorMessage: 'query 不能为空' };
    const limit = Math.min(Math.max(Number(inv.input.limit ?? 5) || 5, 1), 10);

    try {
      const out = await this.webSearch.search(query, limit);
      return {
        ok: true,
        output: {
          query: out.query,
          provider: out.provider,
          results: out.results,
          // 给 LLM 一个明确提示，结果可能 0 条
          note:
            out.results.length === 0
              ? '搜索引擎返回 0 条结果。可能：（1）查询太具体；（2）信息确实不存在；（3）provider 临时受限。'
              : undefined,
        },
      };
    } catch (err) {
      return {
        ok: false,
        errorMessage:
          `网络搜索失败：${(err as Error).message}。` +
          '可能：网络受限 / provider 临时不可用。请告知用户暂时无法访问外部网络。',
      };
    }
  }
}
