import { logger } from '../utils/logger.js';
import axios from 'axios';

export class WebSearchTool {
  constructor() {
    this.name = 'web_search';
    this.description = 'Search the web for information';
  }

  async search(query, options = {}) {
    const { numResults = 5 } = options;

    logger.info(`🔍 Searching web: ${query.substring(0, 100)}...`);

    try {
      // Use DuckDuckGo API (free, no key required)
      const response = await axios.get(
        'https://api.duckduckgo.com/',
        {
          params: {
            q: query,
            format: 'json',
          },
          timeout: 30000,
        }
      );

      const abstract = response.data.Abstract;
      const relatedTopics = response.data.RelatedTopics || [];

      const results = [
        ...(abstract ? [{ title: 'Abstract', snippet: abstract, url: response.data.RelatedTopics?.[0]?.FirstURL }] : []),
        ...relatedTopics
          .filter(t => t.FirstURL)
          .slice(0, numResults - 1)
          .map(t => ({
            title: t.Text,
            snippet: t.FirstURL,
            url: t.FirstURL,
          })),
      ];

      return {
        success: true,
        query,
        results,
        count: results.length,
      };
    } catch (error) {
      logger.error('Web search error:', error.message);
      return {
        success: false,
        error: error.message,
      };
    }
  }
}
