from playwright.sync_api import sync_playwright
import sys
pid=sys.argv[1]
with sync_playwright() as p:
    b=p.chromium.launch(headless=True,args=["--no-sandbox","--disable-dev-shm-usage"])
    ctx=b.new_context(storage_state="/tmp/das_state.json",user_agent="Mozilla/5.0")
    pg=ctx.new_page()
    pg.goto(f"https://dasindonesia.com/wp-admin/post.php?post={pid}&action=edit",timeout=60000,wait_until="domcontentloaded")
    pg.wait_for_timeout(9000)
    # cek tombol save - kalau ada perubahan, tombol jadi "Save"; kalau nggak ada perubahan, mungkin "Update" disabled
    sb=pg.locator("button.editor-post-publish-button")
    if sb.count()>0:
        print("save btn visible:", sb.first.is_visible(), "| text:", sb.first.inner_text(timeout=3000).strip()[:30])
        if sb.first.is_visible():
            sb.first.click()
            print("clicked Save")
            pg.wait_for_timeout(6000)
    else:
        print("no save button found")
    # cek saved state
    try:
        st=pg.locator(".editor-post-saved-state").first
        print("SAVED STATE:", st.inner_text(timeout=3000).strip()[:50] if st.count() else "none")
    except Exception as e:
        print("st err",str(e)[:40])
    # buka Yoast & baca Problems
    b2=pg.locator("button[aria-label*='Yoast']")
    if b2.count()>0: b2.first.click(); pg.wait_for_timeout(2500)
    try: pg.locator("text=SEO analysis").last.click(); pg.wait_for_timeout(2500)
    except: pass
    for anchor in ["Problems","Good results"]:
        try:
            el=pg.locator(f"text={anchor}").last
            if el.count()>0:
                cont=el.locator("xpath=ancestor::*[4]")
                t=cont.inner_text(timeout=4000)
                # ambil bagian sebelum "Improvements" atau "Good"
                import re as _re
                print(f"===== {anchor} =====")
                print(t[:700])
                break
        except Exception as e:
            print("skip",anchor,str(e)[:40])
    b.close()
print("DONE")
