import z from 'zod';
import type { ToolDef } from './types.js';

const schema = z.object({
  url: z.string().url().describe('URL to fetch and extract text from'),
});

export const scrapeUrlTool: ToolDef = {
  name: 'scrape_url',
  description: 'Fetch and extract readable text from a URL. Use when user asks about specific page content.',
  schema,
  execute: async (params, _ctx) => {
    const { url } = schema.parse(params);
    const res = await fetch(url, {
      signal: AbortSignal.timeout(10000),
      headers: { 'User-Agent': 'GooSeek-MasterAgent/1.0' },
    });
    const html = await res.text();
    const title = html.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim() ?? url;
    const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
    const body = bodyMatch ? bodyMatch[1] : html;
    const text = body
      .replace(/<script[\s\S]*?<\/script>/gi, '')
      .replace(/<style[\s\S]*?<\/style>/gi, '')
      .replace(/<[^>]+>/g, ' ')
      .replace(/\s+/g, ' ')
      .trim()
      .slice(0, 8000);
    return JSON.stringify({ title, url, content: text }, null, 2);
  },
};
