'use strict';

async function webSearchTool(config, args, abortSignal) {
  if (abortSignal && abortSignal.aborted) {
    return { success: false, error: '任务被用户取消', cancelled: true };
  }
  const body = {
    api_key: config.tavily_api_key,
    query: args.query,
  };
  if (args.max_results) body.max_results = args.max_results;
  if (args.topic) body.topic = args.topic;
  if (args.time_range) body.time_range = args.time_range;
  if (args.days) body.days = args.days;
  if (args.start_date) body.start_date = args.start_date;
  if (args.end_date) body.end_date = args.end_date;
  if (args.country) body.country = args.country;

  try {
    const res = await fetch('https://api.tavily.com/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
      signal: abortSignal,
    });
    const json = await res.json();
    if (!res.ok) {
      return { success: false, error: json.error || JSON.stringify(json) };
    }
    return { success: true, ...json, query: args.query, searched_at: new Date().toISOString() };
  } catch (err) {
    if (err && err.name === 'AbortError') {
      return { success: false, error: '任务被用户取消', cancelled: true };
    }
    return { success: false, error: err.message || String(err) };
  }
}

async function extractWebpageTool(config, args, savePath, abortSignal) {
  if (abortSignal && abortSignal.aborted) {
    return { success: false, error: '任务被用户取消', cancelled: true };
  }
  const body = {
    api_key: config.tavily_api_key,
    urls: [args.url],
    include_images: false,
  };
  try {
    const res = await fetch('https://api.tavily.com/extract', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
      signal: abortSignal,
    });
    const json = await res.json();
    if (!res.ok) {
      return { success: false, error: json.error || JSON.stringify(json) };
    }
    const content = (json.results && json.results[0] && json.results[0].content) || '';
    if (args.mode === 'save') {
      const fs = require('fs');
      fs.writeFileSync(savePath, content, 'utf8');
      return { success: true, saved_path: savePath, content, chars: content.length, bytes: Buffer.byteLength(content) };
    }
    return { success: true, content, url: args.url };
  } catch (err) {
    if (err && err.name === 'AbortError') {
      return { success: false, error: '任务被用户取消', cancelled: true };
    }
    return { success: false, error: err.message || String(err) };
  }
}

module.exports = { webSearchTool, extractWebpageTool };
