#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""RSIA: upload gambar Pexels via Media (Playwright) lalu set sebagai featured image post 4354."""
import sys, time, json
from playwright.sync_api import sync_playwright

LOGIN_URL="https://rsia.kendangsari.com/wp-login.php"
USER="bambangbot"; PW="C00l_man&314554"
IMG="/tmp/pexels_15511324.jpg"
POST_ID=4348  # 7-tips-melatih-bayi-tengkurap (ganti dari 4354 tali pusar)
IMAGE_FILENAME="innocent-newborn-face-15511324.jpg"
STATE="/tmp/rsiak_state.json"

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

def login(ctx,pg):
    goto_light(pg,"https://rsia.kendangsari.com/wp-admin/")
    for _ in range(20):
        if "wp-login" not in pg.url and "wp-admin" in pg.url: 
            print("LOGIN_OK (state)"); return True
        if pg.locator("#user_login").count()>0: break
        pg.wait_for_timeout(3000)
    if pg.locator("#user_login").count()==0:
        print("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(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 (fresh)"); return True
        if pg.locator("#login_error").count()>0:
            print("LOGIN_ERROR",pg.locator("#login_error").inner_text(timeout=2000)[:120]); return False
    print("LOGIN_TIMEOUT",pg.url); return False

def main():
    with sync_playwright() as p:
        b=p.chromium.launch(headless=True,args=["--no-sandbox","--disable-dev-shm-usage"])
        # coba pakai state yg sudah ada utk hemat waktu login
        import os as _os
        _has_state = _os.path.exists(STATE)
        ctx=b.new_context(storage_state=STATE if _has_state else None,
                          user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
        pg=ctx.new_page()
        if not login(ctx,pg): b.close(); return 1

        # --- Upload via Media -> Add New
        print("=== Upload media ===")
        goto_light(pg,"https://rsia.kendangsari.com/wp-admin/media-new.php",90)
        for _ in range(30):
            pg.wait_for_timeout(3000)
            if pg.locator("input[type='file']").count()>0 or "wp-upload" in pg.url or pg.locator("#media-upload-form").count()>0:
                break
        # coba set file input
        inp=pg.locator("input[type='file']").first
        if inp.count()==0:
            # coba tab "Upload Files"
            try:
                pg.locator("a:has-text('Upload Files')").first.click(no_wait_after=True); pg.wait_for_timeout(4000)
            except Exception: pass
            inp=pg.locator("input[type='file']").first
        if inp.count()==0:
            print("FILE_INPUT_NOT_FOUND"); b.close(); return 1
        inp.set_input_files(IMG)
        print("  file input set, waiting upload...")
        # tunggu thumbnail/attachment id muncul
        mid=None
        for _ in range(30):
            pg.wait_for_timeout(3000)
            att=pg.locator("[data-id], .attachment-preview, #media-items .attachment")
            if att.count()>0:
                try:
                    mid=att.first.get_attribute("data-id")
                    if mid: break
                except Exception: pass
            if "attachment" in pg.locator("body").inner_text(timeout=2000).lower(): pass
        print("  media id =", mid)
        # library mode
        goto_light(pg,"https://rsia.kendangsari.com/wp-admin/upload.php",90)
        for _ in range(30):
            pg.wait_for_timeout(3000)
            if pg.locator("#the-list tr, .attachments, .media-item").count()>0: break

        # --- Set featured image post 4354 via edit page
        print("=== Set featured image post",POST_ID,"===")
        goto_light(pg,f"https://rsia.kendangsari.com/wp-admin/post.php?post={POST_ID}&action=edit",90)
        for _ in range(30):
            pg.wait_for_timeout(3000)
            if pg.locator("#publish").count()>0 or pg.locator("#postimagediv").count()>0: break
        # cek featured image sidebar
        fidiv=pg.locator("#postimagediv")
        print("  has postimagediv:", fidiv.count()>0)
        try:
            setlink=pg.locator("#postimagediv a:has-text('Set featured image'), a[href*='set-post-thumbnail'][href*='4354']").first
            if setlink.count()==0:
                setlink=pg.locator("#postimagediv .inside a").first
            print("  found set-link:", setlink.count()>0)
            setlink.click(no_wait_after=True); pg.wait_for_timeout(4000)
            # di popup gallery, cari "Media Library" tab & pilih item terbaru
            try:
                pg.locator("#menu-item-library").click(no_wait_after=True); pg.wait_for_timeout(4000)
            except Exception:
                try: pg.locator("a:has-text('Media Library')").first.click(no_wait_after=True); pg.wait_for_timeout(4000)
                except Exception: pass
            # pilih attachment terbaru (cari yang setara IMAGE_FILENAME atau data-id)
            sel='.attachments-browser li.attachment, .media-frame-content li.attachment'
            picked=False
            for _ in range(20):
                pg.wait_for_timeout(3000)
                items=pg.locator(sel)
                if items.count()>0:
                    # prefer item dengan judul filename kita
                    target=None
                    for i in range(items.count()):
                        if IMAGE_FILENAME in (items.nth(i).get_attribute("aria-label") or ""):
                            target=items.nth(i); break
                    if target is None: target=items.first
                    target.click(no_wait_after=True); pg.wait_for_timeout(2500); picked=True; break
            print("  picked attachment:", picked)
            # klik Set featured image / Use as featured image
            use=pg.locator("button:has-text('Set featured image'), .button:has-text('Set featured image')").first
            if use.count()==0: use=pg.locator(".button:has-text('Set featured image')").first
            print("  use-btn:",use.count()>0)
            if use.count()>0:
                use.click(no_wait_after=True); pg.wait_for_timeout(4000)
        except Exception as e:
            print("  set-featured err",str(e)[:80])
        # --- Save/Update post
        sb=pg.locator("#publish")
        if sb.count()>0:
            try: print("  btn:",sb.first.inner_text(timeout=3000).strip()[:20])
            except: pass
            sb.first.click(no_wait_after=True)
            print("  clicked Update")
            pg.wait_for_timeout(6000)
        b.close()
    print("DONE (step verify via REST separately)")
    return 0

sys.exit(main())
