#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnostik: login RSIA lalu dump tombol-tombol yang tersedia di editor post 4354
untuk menemukan selector tombol Save/Update yang benar."""
import sys, time
from playwright.sync_api import sync_playwright

USER = "bambangbot"
LOGIN_PW = "C00l_man&314554"
BASE = "https://rsia.kendangsari.com"
STATE = "/tmp/rsiak_state.json"

def goto_light(pg, url, mw=90):
    try:
        pg.goto(url, timeout=mw*1000, wait_until="commit")
    except Exception as e:
        print("goto warn:", str(e)[:60])

def ensure_login(ctx, pg):
    goto_light(pg, f"{BASE}/wp-admin/", 90)
    for _ in range(30):
        if "wp-login" not in pg.url and "wp-admin" in pg.url:
            return True
        if pg.locator("#user_login").count() > 0:
            break
        pg.wait_for_timeout(3000)
    goto_light(pg, f"{BASE}/wp-login.php", 90)
    for _ in range(30):
        if pg.locator("#user_login").count() > 0:
            break
        pg.wait_for_timeout(3000)
    pg.fill("#user_login", USER)
    pg.fill("#user_pass", LOGIN_PW)
    pg.click("#wp-submit", no_wait_after=True)
    for _ in range(50):
        pg.wait_for_timeout(3000)
        if "wp-login" not in pg.url and "wp-admin" in pg.url:
            ctx.storage_state(path=STATE)
            print("LOGIN_OK")
            return True
    print("LOGIN_TIMEOUT", pg.url)
    return False

SELS = [
    "#publish", "button.editor-post-publish-button__button",
    "button.editor-post-publish-button", "div.editor-post-publish-button button",
    "input[name='save']", "input#save-post", "#save-post", "input#save",
]

def main():
    pid = sys.argv[1] if len(sys.argv) > 1 else "4354"
    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()
        if not ensure_login(ctx, pg):
            b.close(); return 1
        url = f"{BASE}/wp-admin/post.php?post={pid}&action=edit"
        goto_light(pg, url, 90)
        # tunggu 60s lebih biar editor render
        for _ in range(20):
            pg.wait_for_timeout(3000)
            # cek apakah page punya block editor (edit-post) atau classic (#postdivrich)
            has_blocks = pg.locator(".block-editor iframe") or pg.locator(".is-desktop")
            if pg.locator("#postdivrich").count() > 0 or pg.locator(".editor-post-publish-button__button").count() > 0:
                break
        print("URL:", pg.url)
        print("classic (#postdivrich):", pg.locator("#postdivrich").count())
        print("block (edit-post root):", pg.locator("body.block-editor-page").count())
        for sel in SELS:
            c = pg.locator(sel).count()
            vis = False
            txt = ""
            if c > 0:
                try:
                    vis = pg.locator(sel).first.is_visible()
                    txt = (pg.locator(sel).first.inner_text(timeout=3000) or "").strip()[:30]
                except Exception as e:
                    txt = f"<err {str(e)[:40]}>"
            print(f"  {sel}: count={c} visible={vis} text='{txt}'")
        b.close()
    print("DIAG_DONE")
    return 0

sys.exit(main())
