import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();

export async function searchWeb(query, count = 5) {
    const apiKey = process.env.BRAVE_API_KEY;
    if (!apiKey) throw new Error('BRAVE_API_KEY is not set in .env');

    try {
        const response = await axios.get('https://api.search.brave.com/res/v1/web/search', {
            params: { q: query, count: Math.min(count, 20) },
            headers: {
                'Accept': 'application/json',
                'X-Subscription-Token': apiKey
            }
        });
        return response.data?.web?.results?.map(r => ({ title: r.title, url: r.url, description: r.description })) || [];
    } catch (err) {
        throw err;
    }
}
