#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""RSIA v3: SET FEATURED IMAGE post 4348 (7-tips-melatih-bayi-tengkurap)
pakai gambar innocent-newborn-face (15511324). Satu sesi Playwright login wp-admin.
Alur: login -> upload native di media-new.php (dapat media id) -> buka editor 4348
-> set featured image lewat media frame -> buka Yoast, pastikan TIDAK ada 'not analyzed'
dan hijau -> Save/Update. Defensif: print progres tiap langkah, nonce fresh via evaluate."""
import sys, os, time, json
from playwright.sync_api import sync_playwright

BASE = "https://rsia.kendangsari.com"
USER = "bambangbot"
PW   = "C00l_man&314554"
IMG  = "/tmp/pexels_15511324.jpg"
POST_ID = 4348
FILENAME = "innocent-newborn-face-15511324.jpg"
STATE = "/tmp/rsiak_state.json"
LOG = "/tmp/rsiak_v3.log"

def log(*a):
    print(*a, flush=True)
    with open(LOG, "a") as f:
        f.write(" ".join(str(x) for x in a) + "\n")

def goto_light(pg, url, w=120):
    try:
        pg.goto(url, timeout=w*1000, wait_until="commit")
        return True
    except Exception as e:
        log("  goto warn:", str(e)[:60]); return False

def ensure_login(ctx, pg):
    goto_light(pg, f"{BASE}/wp-admin/", 120)
    for _ in range(25):
        if "wp-login" not in pg.url and "wp-admin" in pg.url:
            log("  LOGIN_OK (state)"); return True
        if pg.locator("#user_login").count() > 0: break
        pg.wait_for_timeout(2000)
    goto_light(pg, f"{BASE}/wp-login.php", 120)
    for _ in range(25):
        if pg.locator("#user_login").count() > 0: break
        pg.wait_for_timeout(2000)
    if pg.locator("#user_login").count() == 0:
        log("  LOGIN_NOT_READY:", pg.url); return False
    pg.fill("#user_login", USER); pg.fill("#user_pass", PW)
    pg.click("#wp-submit", no_wait_after=True)
    for _ in range(60):
        pg.wait_for_timeout(3000)
        if "wp-login" not in pg.url and "wp-admin" in pg.url:
            ctx.storage_state(path=STATE); log("  LOGIN_OK (fresh)"); return True
        if pg.locator("#login_error").count() > 0:
            log("  LOGIN_ERR:", pg.locator("#login_error").inner_text(timeout=2000)[:120]); return False
    log("  LOGIN_TIMEOUT:", pg.url); return False

def upload_native(pg):
    """Upload di media-new.php (native iframe plupload). Kembalikan media id atau None."""
    log("=== UPLOAD media-new ===")
    goto_light(pg, f"{BASE}/wp-admin/media-new.php", 120)
    inp = None
    for _ in range(50):
        pg.wait_for_timeout(3000)
        if pg.locator("input[type='file']").count() > 0:
            inp = pg.locator("input[type='file']").first; break
        # native: input ada dalam iframe atau langsung; coba toggle tab Upload Files
        try:
            if pg.locator("#plupload-browse-button").count() > 0: break
            if pg.locator("a:has-text('Upload Files')").count() > 0:
                pg.locator("a:has-text('Upload Files')").first.click(no_wait_after=True)
        except Exception: pass
    # kadang file input ada di iframe (plupload)
    if inp is None or inp.count() == 0:
        frames = pg.frames
        for fr in frames:
            try:
                if fr.locator("input[type='file']").count() > 0:
                    inp = fr.locator("input[type='file']").first; break
            except Exception: pass
    if inp is None or inp.count() == 0:
        # fallback: tombol browse plupload
        try:
            if pg.locator("#plupload-browse-button").count() > 0:
                # tombol plupload menyembunyikan input file
                hidden = pg.locator("#plupload-browse-button input[type='file'], #html-upload-form input[type='file'], input#async-upload")
                if hidden.count() > 0: inp = hidden.first
        except Exception: pass
    if inp is None or inp.count() == 0:
        log("  ! input file tak ditemukan"); return None
    try:
        inp.set_input_files(IMG)
    except Exception as e:
        log("  ! set_input_files err:", str(e)[:80]); return None
    log("  file input di-set, tunggu upload...")
    mid = None
    for i in range(80):  # hingga 240s (site lemot)
        pg.wait_for_timeout(3000)
        # media id di DOM [data-id] atau href post.php?post=ID di attachment
        try:
            att = pg.locator("[data-id]")
            if att.count() > 0:
                mid = att.first.get_attribute("data-id"); 
                if mid: log("  media id (data-id) =", mid); return mid
        except Exception: pass
        # redirect ke upload.php library?
        if "upload.php" in pg.url:
            try:
                li = pg.locator("li.attachment")
                if li.count() > 0:
                    a = li.first.locator("a").get_attribute("href") or ""
                    if "post=" in a:
                        mid = a.split("post=")[1].split("&")[0]; log("  media id (library) =", mid); return mid
            except Exception: pass
        if i % 5 == 0: log(f"  ...menunggu upload ke-{i+1}")
    log("  upload timeout, tak ada media id"); return None

def set_featured_editor(pg, mid):
    log("=== SET FEATURED editor post", POST_ID, "===")
    goto_light(pg, f"{BASE}/wp-admin/post.php?post={POST_ID}&action=edit", 120)
    for _ in range(40):
        pg.wait_for_timeout(3000)
        if pg.locator("#postimagediv").count() > 0 or pg.locator("#publish").count() > 0:
            break
    # klik tombol set/remove featured di sidebar
    opened = False
    try:
        link = pg.locator("#postimagediv").first.locator(".inside a").first
        if link.count() > 0:
            link.click(no_wait_after=True); opened = True
    except Exception as e:
        log("  open frame err:", str(e)[:50])
    if not opened:
        log("  ! tak bisa buka media frame"); return False
    pg.wait_for_timeout(4000)
    # pastikan tab Media Library
    try:
        if pg.locator("#menu-item-library").count() > 0: pg.locator("#menu-item-library").click(no_wait_after=True)
        elif pg.locator("a:has-text('Media Library')").first.count() > 0: pg.locator("a:has-text('Media Library')").first.click(no_wait_after=True)
    except Exception: pass
    pg.wait_for_timeout(4000)
    picked = False
    for _ in range(40):
        pg.wait_for_timeout(3000)
        items = pg.locator(".attachments li.attachment, .media-frame-content li.attachment")
        if items.count() > 0:
            target = None
            for i in range(min(items.count(), 80)):
                try:
                    if FILENAME in (items.nth(i).get_attribute("aria-label") or ""): target = items.nth(i); break
                except Exception: pass
            if target is None: target = items.first
            try: target.click(no_wait_after=True)
            except Exception: pass
            pg.wait_for_timeout(2000); picked = True; break
    log("  picked attachment:", picked)
    used = False
    for sel in ["button:has-text('Set featured image')", ".button:has-text('Set featured image')",
                "input#set-post-thumbnail"]:
        b = pg.locator(sel)
        if b.count() > 0:
            try: b.first.click(no_wait_after=True); used = True; log("  klik set:", sel); break
            except Exception: pass
    if not used: log("  ! btn set-featured tak ditemukan")
    pg.wait_for_timeout(5000)
    return used

def ensure_yoast_and_save(pg):
    log("=== YOAST + SAVE ===")
    if "post.php" not in pg.url:
        goto_light(pg, f"{BASE}/wp-admin/post.php?post={POST_ID}&action=edit", 120)
        for _ in range(30):
            pg.wait_for_timeout(3000)
            if pg.locator("#publish").count() > 0 or pg.locator("#postdivrich").count() > 0: break
    # buka metabox Yoast
    opened = False
    try:
        if pg.locator("#wpseo_meta").count() > 0 and pg.locator("#wpseo_meta.hide-if-js").count() == 0:
            # klik handlediv untuk expand bila collapsed
            if pg.locator("#wpseo_meta .handlediv").count() > 0:
                pg.locator("#wpseo_meta .handlediv").first.click(no_wait_after=True); pg.wait_for_timeout(800)
            # klik tab pertama (SEO)
            tab = pg.locator("#wpseo_meta .nav-tab").first
            if tab.count() > 0: tab.click(no_wait_after=True); opened = True
    except Exception as e:
        log("  yoast open err:", str(e)[:50])
    log("  yoast tab dibuka:", opened)
    # deteksi 'not analyzed' berulang lalu trigger analyze
    for _ in range(8):
        pg.wait_for_timeout(2000)
        body = pg.locator("body").inner_text(timeout=6000)
        words = ["not analyzed", "Not analyzed", "Not analyzed by Yoast", "notAnalyzed"]
        hit = any(w in body for w in words)
        log("  not-analyzed?:", hit)
        if hit:
            for sel in ["button:has-text('Analyze')", "a:has-text('Analyze')", ".yoast-analytics trigger",
                        "#yoast-analysis"]:
                b = pg.locator(sel)
                if b.count() > 0:
                    try: b.first.click(no_wait_after=True); log("  trigger analyze:", sel); break
                    except Exception: pass
    # cuplik indikator status Yoast
    try:
        if pg.locator("#wpseo_meta").count() > 0:
            content = pg.locator("#wpseo_meta").inner_text(timeout=7000)
            log("  --- Yoast snippets ---")
            for ln in content.splitlines():
                s = ln.strip()
                if any(w in s.lower() for w in ["good", "problem", "ok", "keyphrase", "readab", "seo", "analy"]):
                    log("   ", s[:130])
    except Exception: pass
    # Save
    sb = pg.locator("#publish")
    if sb.count() > 0:
        try: log("  btn:", sb.first.inner_text(timeout=3000).strip()[:30])
        except Exception: pass
        sb.first.click(no_wait_after=True); pg.wait_for_timeout(6000)
        note = ""
        for _ in range(6):
            pg.wait_for_timeout(2000)
            if pg.locator("#message").count() > 0:
                note = pg.locator("#message").inner_text(timeout=2000).strip()[:200]; break
        log("  after-save:", note or "(no msg)")
        return True
    log("  ! #publish tak ada"); return False

def main():
    if os.path.exists(LOG): os.remove(LOG)
    log("START v3 post", POST_ID)
    if not os.path.exists(IMG): log("! gambar tak ada"); return 1
    with sync_playwright() as p:
        b = p.chromium.launch(headless=True, args=["--no-sandbox","--disable-dev-shm-usage"])
        ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"
        ctx = b.new_context(storage_state=STATE if os.path.exists(STATE) else None, user_agent=ua)
        pg = ctx.new_page()
        if not ensure_login(ctx, pg): b.close(); return 1
        mid = upload_native(pg)
        log("  upload result mid:", mid)
        ok = set_featured_editor(pg, mid)
        log("  set_featured ok:", ok)
        ensure_yoast_and_save(pg)
        b.close()
    log("DONE ok=", ok)
    return 0

sys.exit(main())
