#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnostik + touch-save RSIA (Classic Editor) dengan verifikasi PANEL YOAST:
1) buka post editor
2) buka/cek panel Yoast SEO (metabox), baca Problems/Good results
3) tekan tombol Save/Update (#publish)
Sesuai permintaan Bos: 'masuk sesuai permintaan Yoast lalu tekan tombol Save'.
"""
import sys, json, time
from playwright.sync_api import sync_playwright

STATE = "/tmp/rsiak_state.json"
LOGIN_URL = "https://rsia.kendangsari.com/wp-login.php"
USER = "bambangbot"
PW = "C00l_man&314554"  # password login asli (bukan app password)

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

def ensure_login(ctx, pg):
    # coba state dulu
    goto_light(pg, LOGIN_URL.replace("wp-login.php","wp-admin/"), 60)
    for _ in range(20):
        if "wp-login" not in pg.url and "wp-admin" in pg.url:
            print("LOGIN_OK (via state)")
            return True
        if pg.locator("#user_login").count()>0:
            break
        pg.wait_for_timeout(3000)
    if pg.locator("#user_login").count()>0:
        pg.fill("#user_login", USER)
        pg.fill("#user_pass", 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:
                ctx.storage_state(path=STATE)
                print("LOGIN_OK (fresh), state saved")
                return True
            if pg.locator("#login_error").count()>0:
                print("LOGIN_ERROR:", pg.locator("#login_error").inner_text(timeout=2000)[:150])
                return False
    print("LOGIN_NOT_READY url:", pg.url)
    return False

def open_yoast(pg):
    """Coba buka panel Yoast di classic editor (bisa metabox bawah / sidebar)."""
    found = []
    # Sinar: tab/menubar Yoast
    for sel in ["#wpseo-meta-tab", "a[href*='wpseo_meta']", "li#wpseo-meta-tab"]:
        if pg.locator(sel).count()>0:
            try:
                pg.locator(sel).first.click(no_wait_after=True)
                pg.wait_for_timeout(1500)
                found.append(sel)
            except Exception:
                pass
    # Cek konten Yoast muncul
    yo_anchors = ["Problems", "Good results", "Remove", "SEO", "Readability"]
    hit = []
    for a in yo_anchors:
        try:
            el = pg.locator(f"text={a}").last
            if el.count()>0:
                hit.append(a)
        except Exception:
            pass
    return {"tabs_clicked": found, "yoast_content_seen": hit}

def run():
    pids_str = sys.argv[1]
    pids = [int(x) for x in pids_str.split(",") if x.strip()]
    out = {}
    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):
            print("ABORT login"); b.close(); return 1
        for i, pid in enumerate(pids, 1):
            res = {"id": pid}
            print(f"\n--- [{i}/{len(pids)}] PID {pid} ---")
            goto_light(pg, f"https://rsia.kendangsari.com/wp-admin/post.php?post={pid}&action=edit", 90)
            # tunggu classic editor ready (#publish) atau title
            ready = False
            for _ in range(30):
                pg.wait_for_timeout(3000)
                if pg.locator("#publish").count()>0:
                    ready = True; break
            if not ready:
                res["status"]="EDITOR_NOT_READY"; out[str(pid)]=res; print(pid,"EDITOR_NOT_READY"); continue
            # BUKA YOAST dulu (sesuai permintaan Bos)
            y = open_yoast(pg)
            res["yoast"] = y
            # baca teks panel Yoast bila ada
            yoast_txt = ""
            try:
                box = pg.locator("#wpseo_meta, .yoast-issue-wrapper, .wpseo-metabox")
                if box.count()>0:
                    yoast_txt = box.first.inner_text(timeout=5000)[:500]
            except Exception:
                pass
            res["yoast_preview"] = yoast_txt[:300]
            print("  yoast opened:", y, "| preview:", yoast_txt[:150].replace("\n"," "))
            # TEKAN SAVE (tombol Update classic editor)
            sb = pg.locator("#publish")
            btn_txt = ""
            if sb.count()>0:
                try: btn_txt = sb.first.inner_text(timeout=3000).strip()[:20]
                except Exception: pass
                try:
                    sb.first.click(no_wait_after=True)
                except Exception as e:
                    print("  click err", str(e)[:60])
            # tunggu pesan tersimpan (saved)
            saved = False
            for _ in range(15):
                pg.wait_for_timeout(3000)
                try:
                    txt = pg.locator("#message, .notice-success, #publishing-action .spinner").first.inner_text(timeout=2000)
                    if "updated" in txt.lower() or "Update" in txt:
                        saved = True
                    if pg.locator("#wpbody-content .notice-success").count()>0:
                        saved=True
                except Exception:
                    pass
                if saved: break
            res["status"] = "SAVED" if saved else "CLICKED_UNVERIFIED"
            res["btn"] = btn_txt
            out[str(pid)] = res
            print(f"  PID {pid} -> {res['status']} (btn='{btn_txt}')")
            time.sleep(2)
        b.close()
    json.dump(out, open("/tmp/rsia_touchsave_yoast.json","w"), indent=2, ensure_ascii=False)
    print("\nSAVED /tmp/rsia_touchsave_yoast.json")
    return 0

sys.exit(run())
