#!/usr/bin/env python3
"""Ambil isi artikel Medium dengan peramban sungguhan, lalu simpan teksnya."""
import asyncio, re

URL = ("https://dkspeaks.medium.com/how-to-grow-on-threads-the-real-strategy-that-took-me-"
       "from-0-to-2-000-followers-in-45-days-8b150f4c9eee")
KELUAR = "/home/mantapman/.hermes/profiles/atun/workspace/drafts/artikel_threads_medium.txt"


async def main():
    from playwright.async_api import async_playwright
    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()
        await hal.goto(URL, wait_until="domcontentloaded", timeout=90000)
        await hal.wait_for_timeout(6000)
        # tutup dialog kalau muncul
        for teks_tombol in ("Dismiss", "Sign in", "Close", "Got it"):
            try:
                t = hal.get_by_role("button", name=re.compile(teks_tombol, re.I))
                if await t.count():
                    await t.first.click()
                    await hal.wait_for_timeout(1500)
            except Exception:
                pass
        judul = await hal.title()
        isi = await hal.evaluate("""
        () => {
          const el = document.querySelector('article') || document.body;
          return el.innerText;
        }""")
        await br.close()

    isi = re.sub(r"\n{3,}", "\n\n", isi)
    baris = [b.strip() for b in isi.split("\n") if b.strip()]
    print(f"judul: {judul[:110]}")
    print(f"total baris: {len(baris)}\n")
    for b in baris[:150]:
        print("   " + b[:210])
    open(KELUAR, "w").write(judul + "\n\n" + "\n".join(baris))
    print(f"\n→ {KELUAR}")


asyncio.run(main())
