import { prisma } from "../lib/db";
import { createContext } from "../lib/threads-browser/browser";

async function main() {
  const account = await prisma.account.findFirst({ orderBy: { updatedAt: "desc" } });
  if (!account) return;

  const context = await createContext(account.storageState, true);
  const page = await context.newPage();

  let jsonHits = 0;
  page.on("response", async (response) => {
    const url = response.url();
    if (!url.includes("graphql") && !url.includes("threads") && !url.includes("instagram")) return;
    try {
      const ct = response.headers()["content-type"] ?? "";
      if (!ct.includes("json")) return;
      const text = await response.text();
      if (text.includes("caption") || text.includes("thread_items")) jsonHits++;
    } catch {}
  });

  const searchUrl = `https://www.threads.com/search?q=${encodeURIComponent("備孕")}&serp_type=default`;
  await page.goto(searchUrl, { waitUntil: "domcontentloaded", timeout: 60000 });
  await page.waitForTimeout(2000);
  console.log("After goto:", page.url());
  console.log("Body has 404?:", (await page.locator("body").innerText()).includes("走丟"));

  for (let i = 0; i < 5; i++) {
    await page.mouse.wheel(0, 1200);
    await page.waitForTimeout(1500);
  }

  const articles = await page.locator('div[role="article"]').count();
  const posts = await page.locator('a[href*="/post/"]').count();
  const pressable = await page.locator('[data-pressable-container="true"]').count();
  const dirAuto = await page.locator('div[dir="auto"]').count();
  console.log({ articles, posts, pressable, dirAuto, jsonHits });

  const scripts = await page.locator('script[type="application/json"][data-sjs]').count();
  console.log("script tags:", scripts);

  await context.close();
}

main().catch(console.error);