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) {
    console.log("No account");
    return;
  }

  const query = process.argv[2] ?? "備孕";
  const context = await createContext(account.storageState, false);
  const page = await context.newPage();

  const apiUrls: string[] = [];
  page.on("response", async (response) => {
    const url = response.url();
    if (url.includes("graphql") || url.includes("/api/") || url.includes("barcelona")) {
      apiUrls.push(url.split("?")[0]);
      try {
        const ct = response.headers()["content-type"] ?? "";
        if (ct.includes("json")) {
          const json = await response.json();
          const str = JSON.stringify(json);
          if (str.includes("caption") || str.includes("text_post") || str.includes("thread_items")) {
            console.log("[HIT]", url.slice(0, 120));
            console.log("[SNIP]", str.slice(0, 300));
          }
        }
      } catch {
        // ignore
      }
    }
  });

  const searchUrl = `https://www.threads.com/search?q=${encodeURIComponent(query)}&serp_type=default`;
  console.log("Navigating to:", searchUrl);
  await page.goto(searchUrl, { waitUntil: "networkidle", timeout: 90000 });
  await page.waitForTimeout(5000);

  console.log("Final URL:", page.url());
  console.log("Title:", await page.title());

  const selectors = [
    'div[role="article"]',
    "article",
    'a[href*="/post/"]',
    'div[dir="auto"]',
    '[data-pressable-container="true"]',
  ];
  for (const sel of selectors) {
    const count = await page.locator(sel).count();
    console.log(`Selector ${sel}: ${count}`);
  }

  const bodyText = await page.locator("body").innerText();
  console.log("Body preview:", bodyText.slice(0, 500).replace(/\n/g, " | "));

  console.log("Unique API URLs:", [...new Set(apiUrls)].slice(0, 20));

  await page.screenshot({ path: "/Users/daniel/Desktop/threadTools/debug-search.png", fullPage: true });
  console.log("Screenshot saved");

  await context.close();
}

main().catch(console.error);