#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Login ulang ke dasindonesia.com/wp-admin (fresh), simpan state,
lalu scan daftar post terjadwal (future) & draft terbaru."""
import json, sys
from playwright.sync_api import sync_playwright

USER = "bambangbot"
APP_PW = "VzXR 72KF NJWn XxHI MhJN B9Hs"
STATE = "/tmp/das_state.json"

def goto_light(pg, url, max_wait=60):
    """Navigasi tanpa nunggu load penuh, polling sampai elemen target muncul."""
    try:
        pg.goto(url, timeout=max_wait*1000, wait_until="commit")
    except Exception as e:
        print("  goto warn:", str(e)[:60])

def main():
    with sync_playwright() as p:
        b = p.chromium.launch(headless=True, args=["--no-sandbox","--disable-dev-shm-usage"])
        ctx = b.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
        pg = ctx.new_page()

        # ---- LOGIN FRESH ----
        goto_light(pg, "https://dasindonesia.com/wp-login.php")
        for _ in range(40):
            if pg.locator("#user_login").count()>0 or "wp-admin" in pg.url:
                break
            pg.wait_for_timeout(3000)
        if pg.locator("#user_login").count()==0 and "wp-admin" not in pg.url:
            print("LOGIN PAGE NOT READY, url:", pg.url); b.close(); return 1

        pg.fill("#user_login", USER)
        pg.fill("#user_pass", APP_PW)
        pg.click("#wp-submit", no_wait_after=True)

        logged_in = False
        for _ in range(40):  # max 40*3 = 120s
            pg.wait_for_timeout(3000)
            u = pg.url
            if "wp-login" not in u and "wp-admin" in u:
                logged_in = True
                break
            # masih di login: cek ada error?
            if pg.locator("#login_error").count()>0:
                try: print("LOGIN_ERROR:", pg.locator("#login_error").inner_text(timeout=2000)[:200])
                except Exception: pass
                break
        if not logged_in:
            print("LOGIN_FAILED url:", pg.url); b.close(); return 1

        print("LOGIN_OK url:", pg.url)
        ctx.storage_state(path=STATE)
        print("STATE_SAVED:", STATE)

        # ---- SCAN SCHEDULED (future) ----
        out = {}
        for label, status in [("scheduled","future"), ("draft","draft")]:
            pg.goto(f"https://dasindonesia.com/wp-admin/edit.php?post_status={status}&post_type=post",
                    timeout=90000, wait_until="commit")
            found = False
            for _ in range(25):  # 75s
                pg.wait_for_timeout(3000)
                if pg.locator("table.wp-list-table tbody tr").count()>0:
                    found=True; break
                if pg.locator("tbody.no-items").count()>0:
                    found=True; break
            rows = pg.locator("table.wp-list-table tbody tr")
            n = rows.count()
            print(f"[{label}] rows={n}")
            lst=[]
            for i in range(n):
                r = rows.nth(i)
                try:
                    a = r.locator("td.post-title a.row-title").first
                    title = a.inner_text(timeout=4000).strip()
                    href = a.get_attribute("href") or ""
                    pid = href.split("post=")[1].split("&")[0] if "post=" in href else None
                    if not title:
                        s = r.locator(".post-title strong").first
                        if s.count(): title = s.inner_text(timeout=3000).strip()
                    lst.append({"id":pid,"title":title})
                    print(f"   {pid} | {title[:55]}")
                except Exception as e:
                    print(f"   row{i} err: {str(e)[:50]}")
            out[label]=lst

        with open("/tmp/das_posts.json","w") as f:
            json.dump(out,f,indent=2,ensure_ascii=False)
        print("SAVED /tmp/das_posts.json")
        b.close()
        return 0

sys.exit(main())
