import { defineFn } from "@browserbasehq/sdk-functions";
import { browserbase, Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod/v4";

// This is your first Browserbase function!
// You can run it locally with: bb dev index.ts
// Once ready, publish it with: bb publish index.ts

defineFn(
  "my-function",
  async (context) => {
    const browser = await browserbase.connect({
      // The local dev server has no secrets, so fall back to .env.
      apiKey:
        context.secrets.BROWSERBASE_API_KEY ?? process.env.BROWSERBASE_API_KEY!,
      sessionId: context.session.id,
    });
    // In this example, Stagehand uses the Model Gateway where Browserbase charges for the tokens
    const stagehand = await Stagehand.create({ browser });
    const page = (await browser.context.activePage())!;

    await page.goto("https://news.ycombinator.com");
    const { data } = await stagehand.extract(
      "Extract the top 3 stories with their rank, title, and link URL.",
      z.object({
        stories: z
          .array(z.object({ rank: z.number(), title: z.string(), url: z.string() }))
          .max(3),
      }),
    );

    await stagehand.close();
    return {
      message: "Successfully fetched top Hacker News stories",
      timestamp: new Date().toISOString(),
      results: data.stories,
    };
  },
  {
    // Upload the Stagehand extension once, then paste its ID here:
    //   browse cloud extensions upload node_modules/@browserbasehq/stagehand/dist/assets/stagehand-extension.zip
    sessionConfig: { extensionId: "your-extension-id" },
  },
);
