#!/usr/bin/env python3
"""Cari lebih banyak sumber tentang strategi pertumbuhan Threads (dan cara kerja algoritmanya)."""
import asyncio, re, json

TANYA = [
    "Threads algorithm how it works growth strategy 2026",
    "how to grow on Threads engagement tips",
    "Threads reach engagement data study",
    "apa itu threads cara kerja algoritma threads",
]
KELUAR = "/home/mantapman/.hermes/profiles/atun/workspace/drafts/riset_threads_sumber.json"


async def main():
    from playwright.async_api import async_playwright
    hasil = {}
    async with async_playwright() as pw:
        br = await pw.chromium.launch()
        ctx = await br.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36",
                                   locale="en-US")
        hal = await ctx.new_page()
        for q in TANYA:
            u = "https://www.bing.com/search?q=" + q.replace(" ", "+") + "&setlang=en&count=20"
            try:
                await hal.goto(u, wait_until="domcontentloaded", timeout=80000)
                await hal.wait_for_timeout(4000)
                blok = await hal.query_selector_all("li.b_algo")
                temuan = []
                for b in blok[:12]:
                    try:
                        a = await b.query_selector("h2 a")
                        href = await a.get_attribute("href") if a else ""
                        teks = (await b.inner_text()).replace("\n", " | ")[:260]
                        if href and href.startswith("http"):
                            temuan.append({"url": href.split("?")[0], "ringkas": teks})
                    except Exception:
                        continue
                hasil[q] = temuan
                print(f"\n=== {q} ({len(temuan)} hasil) ===")
                for t in temuan:
                    print(f"   {t['url'][:95]}")
                    print(f"      {t['ringkas'][:200]}")
            except Exception as e:
                print(f"\n=== {q} → gagal {str(e)[:70]}")
        await br.close()
    json.dump(hasil, open(KELUAR, "w"), indent=1, ensure_ascii=False)
    print(f"\n→ {KELUAR}")


asyncio.run(main())
