/**
 * `web_fetch` tool —— 抓取**已知 URL** 的页面内容（区别于按关键词搜的 web_search）。
 *
 * 典型场景：
 * - LLM 调 web_search 拿到 5 个结果 URL → 想"读全文"再总结 → 调 web_fetch
 * - 用户直接粘 URL："总结一下 https://..." → LLM 调 web_fetch
 *
 * Provider 走 WebFetchService 内部 auto-detect（Tavily /extract > native fetch 兜底）。
 */

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

@Injectable()
export class WebFetchTool implements AgentTool {
  constructor(private readonly webFetch: WebFetchService) {}

  readonly descriptor: ToolDescriptor = {
    name: 'web_fetch',
    description:
      '抓取**指定 URL** 的页面正文（已知 URL 用此工具）。' +
      '常用：① web_search 返回 URL 后想读全文 ② 用户直接粘 URL 求总结。' +
      '只支持 http/https；返回 markdown 化正文（最长 10k 字符）。' +
      '想按关键词找站点用 web_search，不要用 web_fetch。',
    inputSchema: {
      url: {
        type: 'string',
        required: true,
        description: 'http(s) URL，例 https://en.wikipedia.org/wiki/Transformer',
      },
    },
    availability: { surface: ['web', 'desktop', 'mobile', 'teams', 'cli'] },
  };

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

    try {
      const out = await this.webFetch.fetch(url);
      return {
        ok: true,
        output: {
          url: out.url,
          title: out.title,
          content: out.content,
          provider: out.provider,
          rawLength: out.rawLength,
          truncated: out.truncated,
        },
      };
    } catch (err) {
      return {
        ok: false,
        errorMessage:
          `抓取失败：${(err as Error).message}。` +
          '可能：① URL 不可达 ② 站点拒绝爬虫 ③ 网络受限。可告知用户改用 web_search。',
      };
    }
  }
}
