"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.googleSearchDefinition = void 0;
exports.googleSearch = googleSearch;
const http_1 = __importDefault(require("../../utils/http"));
function transformGoogleSearchResponseForLLM(apiResponse) {
    const searchQuery = apiResponse.queries?.request?.[0]?.searchTerms || "Unknown query";
    const totalResults = apiResponse.searchInformation?.totalResults;
    const relevantItems = (apiResponse.items || []).map((item) => {
        let bestSnippet = item.snippet || "";
        const metaTags = item.pagemap?.metatags?.[0];
        if (metaTags) {
            const ogDescription = metaTags["og:description"];
            const twitterDescription = metaTags["twitter:description"];
            const genericDescription = metaTags?.description;
            if (ogDescription && ogDescription.length > bestSnippet.length) {
                bestSnippet = ogDescription;
            }
            else if (twitterDescription &&
                twitterDescription.length > bestSnippet.length) {
                bestSnippet = twitterDescription;
            }
            else if (genericDescription &&
                genericDescription.length > bestSnippet.length) {
                bestSnippet = genericDescription;
            }
        }
        return {
            title: item.title,
            link: item.link,
            snippet: bestSnippet,
            source: item.displayLink,
        };
    });
    return {
        searchQuery,
        totalResults,
        results: relevantItems,
        usd_cost: 0.005,
    };
}
async function googleSearch(params) {
    const apiKey = process.env.GOOGLE_SEARCH_API_KEY;
    const cx = process.env.GOOGLE_SEARCH_CX;
    if (!apiKey) {
        throw new Error("GOOGLE_SEARCH_API_KEY environment variable is not set");
    }
    if (!cx) {
        throw new Error("GOOGLE_SEARCH_CX environment variable is not set");
    }
    const baseUrl = "https://www.googleapis.com/customsearch/v1";
    const url = new URL(baseUrl);
    url.searchParams.append("key", apiKey);
    url.searchParams.append("cx", cx);
    for (const [key, value] of Object.entries(params)) {
        if (value !== undefined) {
            url.searchParams.append(key, value.toString());
        }
    }
    try {
        const response = await http_1.default.get(url.toString());
        return transformGoogleSearchResponseForLLM(response.data);
    }
    catch (error) {
        console.error("Error performing Google search:", error);
        throw error;
    }
}
exports.googleSearchDefinition = {
    type: "function",
    function: {
        name: "googleSearch",
        description: "Perform a Google search using the Custom Search API",
        parameters: {
            type: "object",
            properties: {
                q: {
                    type: "string",
                    description: "The search query",
                },
                num: {
                    type: "number",
                    description: "The number of search results to return (optional, default is 10, max is 10)",
                },
                start: {
                    type: "number",
                    description: "The index of the first result to return (optional, default is 1)",
                },
                dateRestrict: {
                    type: "string",
                    description: "Restricts results to URLs based on date. Format: [d|w|m|y]NUMBER. Example: 'd10' for past 10 days",
                },
                siteSearch: {
                    type: "string",
                    description: "Specifies a site to search within",
                },
                siteSearchFilter: {
                    type: "string",
                    description: "Controls whether to include or exclude results from the site specified in siteSearch. 'e' to exclude, 'i' to include",
                },
                sort: {
                    type: "string",
                    description: "The sort expression to apply to the results, e.g., 'date'",
                },
                lr: {
                    type: "string",
                    description: "Restricts the search to documents written in a particular language (e.g., lr=lang_ja)",
                },
            },
            required: ["q"],
        },
    },
};
exports.default = googleSearch;
//# sourceMappingURL=googleSearch.js.map