"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/services/gemeniStockMarketConditions.ts
var gemeniStockMarketConditions_exports = {};
__export(gemeniStockMarketConditions_exports, {
  gemeniStockMarketConditions: () => gemeniStockMarketConditions
});
module.exports = __toCommonJS(gemeniStockMarketConditions_exports);
var import_googleapis = require("googleapis");
var import_generative_ai = require("@google/generative-ai");

// src/utils/Extractors.ts
function extractJsonFromBackticks(text) {
  const regex = /```(?:json)?\s*([\s\S]+?)```/;
  const match = text.match(regex);
  return match ? match[1].trim() : text;
}

// src/services/gemeniStockMarketConditions.ts
var import_playwright = __toESM(require("playwright"), 1);
var SEARCH_API_KEY = process.env.GOOGLE_SEARCH_API_KEY;
var SEARCH_ENGINE_ID = process.env.GOOGLE_SEARCH_ENGINE_MARKETS;
var GEMINI_API_KEY = process.env.GEMINI_API_KEY;
var customSearch = import_googleapis.google.customsearch("v1");
var genAI = new import_generative_ai.GoogleGenerativeAI(GEMINI_API_KEY);
var geminiFlashModel = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
var geminiProModel = genAI.getGenerativeModel({ model: "gemini-1.5-pro-001" });
async function loadPageContent(results) {
  if (!results) {
    return [];
  }
  const browser = await import_playwright.default.chromium.launch();
  const pageContents = [];
  for (const result of results) {
    if (result.link && result.snippet && result.title) {
      try {
        console.log("Connected! Navigating...");
        const page = await browser.newPage();
        await page.goto(result.link, { waitUntil: "networkidle", timeout: 2 * 60 * 1e3 });
        console.log("Navigated! Scraping page content...");
        const textContent = await page.innerText("body", { timeout: 2 * 60 * 1e3 });
        if (textContent) {
          pageContents.push(textContent);
        }
      } catch (e) {
        console.log(e);
      }
    }
  }
  await browser.close();
  return pageContents;
}
async function synthesizeAnswer(summaries, originalQuery) {
  if (!summaries || summaries.length === 0) {
    return "No relevant information found.";
  }
  const prompt = `You are a helpful AI analyst tasked with helping users understand the current market conditions. You always format your responses per the users instructions and use tables to format key facts and figures. Using only the following information:

${summaries.join("\n\n")} 

 Generate a market report for the users query: "${originalQuery}"`;
  const geminiProResponse = await geminiProModel.generateContent(prompt);
  return geminiProResponse.response?.text() ?? "Could not synthesize an answer.";
}
async function performSearch(query, numResults = 5) {
  if (!SEARCH_API_KEY || !SEARCH_ENGINE_ID) {
    throw new Error("Search API key or Search Engine ID missing.");
  }
  try {
    const response = await customSearch.cse.list({
      cx: SEARCH_ENGINE_ID,
      q: query,
      auth: SEARCH_API_KEY,
      num: numResults,
      dateRestrict: "d1"
      // Restricts results to the last 24 hours
      //siteSearch: 'finance.yahoo.com',
      //siteSearchFilter: 'i',
    });
    return response.data;
  } catch (error) {
    console.error("Error during search:", error);
    throw error;
  }
}
async function generateSearchQueries(userInput) {
  const prompt = `You are a helpful AI market analyst that specializes in writing search queries based on the user query.
    You carefully deconstruct keywords for the search queries to ensure the user gets valid search results
    Users tend to supply lots of information in their queries and passing this directly to the search engine will cause it to return null results
    Decompose the following user query into the required number of searches to cover their request while obtaining valid search results: 
    "${userInput}"
    You can only respond in JSON in the following format:
    {
        "queries": ["<QUERY_1>", "<QUERY_2>", "<QUERY_3>"...]
    }
    
    for example is the user asks: "what are the current market indices doing, who are the top movers"
    You respond with:
    {
        "queries": ["current VIX level", "what is the current QQQ Index Level", "What is the current SPX level", "top stock market winners today", "top stock market losers today", "top stock market sectors today"]
    }
    Explanation: They query is broken out into separate queries so the search engine will return valid results. There is timeliness to each query limiting the results to the last 24 hours.
    `;
  const geminiProResponse = await geminiFlashModel.generateContent(prompt);
  const result = geminiProResponse.response?.text() ?? "Could not synthesize an answer.";
  const clean = JSON.parse(extractJsonFromBackticks(result));
  return clean.queries;
}
async function researchAssistant(userInput) {
  const queries = await generateSearchQueries(userInput);
  const searchPromises = queries.map((query) => performSearch(query));
  const searchResults = await Promise.all(searchPromises);
  const flattenedResults = searchResults.reduce((acc, curr) => {
    if (curr.items && curr.items.length > 0) {
      acc = [...acc, ...curr.items];
    }
    return acc;
  }, []);
  const summaries = await loadPageContent(flattenedResults);
  return synthesizeAnswer(summaries, userInput);
}
async function gemeniStockMarketConditions(userInput) {
  const answer = await researchAssistant(userInput);
  return answer;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  gemeniStockMarketConditions
});
