#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""RSIA: upload K-MANYA webp (resize max 1000x567) via Playwright wp-admin Media Library,
return mapping local file -> media id ke JSON. Lalu (pemanggil) set featured via REST.
Satu sesi login wp-admin (password asli), upload loop, ambil media id dari redirect/upload.php.
Input: daftar file di WORK/*.webp yg mau diupload (list dari file list_path).
Output: /tmp/rsia_norm/uploaded.json {absolutpath: media_id}
"""
import os, sys, json, time
from playwright.sync_api import sync_playwright

BASE="https://rsia.kendangsari.com"
USER="bambangbot"; PW="C00l_man&314554"
STATE="/tmp/rsiak_state.json"
WORK="/tmp/rsia_norm"; os.makedirs(WORK,exist_ok=True)
LISTF=f"{WORK}/to_upload.txt"   # satu path per baris
OUTF=f"{WORK}/uploaded.json"
LOG=f"{WORK}/upload_log.txt"

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")
    except Exception as e: log("  goto warn",str(e)[:60])

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"); return True
        if pg.locator("#user_login").count(): 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(): break
        pg.wait_for_timeout(2000)
    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(): log("LOGIN_ERR"); return False
    log("LOGIN_TIMEOUT"); return False

def upload_one(pg, path):
    """Navigasi ke media-new, set file, tunggu upload.php, ambil media id pertama kotak terbaru."""
    goto_light(pg,f"{BASE}/wp-admin/media-new.php",120)
    inp=None
    for _ in range(40):
        pg.wait_for_timeout(3000)
        if pg.locator("input[type='file']").count():
            inp=pg.locator("input[type='file']").first; break
        elif pg.frame_locator("iframe").first.locator("input[type='file']").count():
            inp=pg.frame_locator("iframe").first.locator("input[type='file']").first; break
        try:
            if pg.locator("a:has-text('Upload Files')").count():
                pg.locator("a:has-text('Upload Files')").first.click(no_wait_after=True)
        except Exception: pass
    if inp is None:
        # fallback: file input hidden di plupload div
        for sel in ["#plupload-browse-button input[type=file]","input#async-upload","#html-upload input[type=file]"]:
            if pg.locator(sel).count(): inp=pg.locator(sel).first; break
    if inp is None:
        log("  ! input file tak ada"); return None
    try:
        inp.set_input_files(path)
    except Exception as e:
        log("  ! set file err",str(e)[:80]); return None
    # tunggu sampai redirect ke upload.php dan ada attachment tr
    for i in range(60):  # 180s
        pg.wait_for_timeout(3000)
        if "upload.php" in pg.url:
            try:
                rows=pg.locator("#the-list tr.attachment, li.attachment")
                first=pg.locator("#the-list tr.attachment, li.attachment").first
                a=first.locator("a").get_attribute("href") or ""
                if "post=" in a:
                    mid=a.split("post=")[1].split("&")[0]
                    log("  media id:",mid); return mid
            except Exception: pass
        if i%6==0: 
            pass
    # coba ambil dari DOM [data-id]
    try:
        att=pg.locator("[data-id]").first
        if att.count(): 
            mid=att.get_attribute("data-id")
            if mid: log("  media id(data-id):",mid); return mid
    except Exception: pass
    log("  timeout upload"); return None

def main():
    if not os.path.exists(LISTF):
        log("list kosong:",LISTF); return 1
    files=[l.strip() for l in open(LISTF) if l.strip()]
    log("to upload:",len(files))
    result={}
    if os.path.exists(OUTF):
        result=json.load(open(OUTF))
    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) 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
        for f in files:
            if f in result: continue
            mid=upload_one(pg,f)
            result[f]=mid
            json.dump(result,open(OUTF,'w'),indent=1)
        b.close()
    ok=[k for k,v in result.items() if v]
    log("\nuploaded ok:",len(ok),"/",len(files))

sys.exit(main())
