#!/usr/bin/env python3
"""TSLaw: buat dua artikel listikel (foto Pexels, kategori, tag, meta Yoast, tombol WA, schema FAQ).
Alur: unggah foto → buat sebagai draft → verifikasi → terbitkan. Jalankan --apply."""
import base64, json, os, re, sys, time, urllib.request, urllib.error
from xml.sax.saxutils import escape
from PIL import Image

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from tslaw_listikel_1 import ARTIKEL as ART1
from tslaw_listikel_2 import A2

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
os.makedirs(OUT, exist_ok=True)
KATEGORI = [14]          # Hukum Bisnis (kategori yang dipakai artikel lain)
TUJUAN = (1000, 567)

ARTIKEL = [ART1[0], A2]


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:300]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def rpc(method, params=()):
    def val(v):
        if isinstance(v, bool):
            return f"<value><boolean>{1 if v else 0}</boolean></value>"
        if isinstance(v, int):
            return f"<value><int>{v}</int></value>"
        if isinstance(v, list):
            return "<value><array><data>" + "".join(val(x) for x in v) + "</data></array></value>"
        if isinstance(v, dict):
            return "<value><struct>" + "".join(f"<member><name>{escape(str(k))}</name>{val(x)}</member>"
                                               for k, x in v.items()) + "</struct></value>"
        return f"<value><string>{escape(str(v))}</string></value>"
    body = ("<?xml version=\"1.0\"?><methodCall><methodName>" + method + "</methodName><params>" +
            "".join(f"<param>{val(p)}</param>" for p in params) + "</params></methodCall>").encode()
    r = urllib.request.Request(f"https://www.{DOM}/xmlrpc.php", data=body,
                               headers={"Content-Type": "text/xml", "User-Agent": "Mozilla/5.0",
                                        "Authorization": f"Basic {AUTH}"}, method="POST")
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, x.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode("utf-8", "replace")[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def siapkan_foto(pexels_id, nama):
    u = f"https://images.pexels.com/photos/{pexels_id}/pexels-photo-{pexels_id}.jpeg?auto=compress&cs=tinysrgb&w=1400"
    data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=90).read()
    tmp = f"{OUT}/_tmp_{nama}.jpg"
    open(tmp, "wb").write(data)
    im = Image.open(tmp).convert("RGB")
    tw, th = TUJUAN
    w, h = im.size
    r = tw / th
    im = im.crop(((w - int(h * r)) // 2, 0, (w - int(h * r)) // 2 + int(h * r), h)) if w / h > r else \
         im.crop((0, (h - int(w / r)) // 2, w, (h - int(w / r)) // 2 + int(w / r)))
    f = f"{OUT}/{nama}"
    im.resize(TUJUAN, Image.LANCZOS).save(f, "WEBP", quality=90)
    os.remove(tmp)
    return f


print("=== PERSIAPAN ===")
for a in ARTIKEL:
    if "kata" not in a:
        teks = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", a["isi"], flags=re.S | re.I)
        a["kata"] = len([w for w in re.split(r"\s+", re.sub(r"<[^>]+>", " ", teks)) if w])
    a["foto"] = siapkan_foto(a["pexels"], a["slug"] + ".webp")
    print(f"  {a['slug']:<38} {a['kata']:>5} kata | foto {os.path.getsize(a['foto'])//1024} KB | meta {len(a['meta'])} char")

if "--apply" not in sys.argv:
    print("\n(dry run — pakai --apply untuk membuat di WordPress)")
    sys.exit(0)

print("\n=== MEMBUAT DI WORDPRESS (status draft) ===")
hasil = []
for a in ARTIKEL:
    # 1. unggah foto
    st, med = rest("/wp-json/wp/v2/media", "POST", None) if False else (None, None)
    h = {"Authorization": f"Basic {AUTH}", **UA,
         "Content-Type": "image/webp", "Content-Disposition": f'attachment; filename="{a["slug"]}.webp"'}
    req = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media", data=open(a["foto"], "rb").read(),
                                 headers=h, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=180) as x:
            med = json.loads(x.read()); st = x.status
    except urllib.error.HTTPError as e:
        st, med = e.code, e.read().decode()[:200]
    if st not in (201, 200):
        print(f"  GAGAL unggah foto {a['slug']}: {st} {str(med)[:150]}")
        continue
    mid = med["id"]
    rest(f"/wp-json/wp/v2/media/{mid}", "POST", {"alt_text": a.get("alt", a["judul"]), "title": a["judul"]})
    print(f"  foto → media #{mid}")

    # 2. buat artikel (draft)
    payload = {"title": a["judul"], "slug": a["slug"], "content": a["isi"], "status": "draft",
               "categories": KATEGORI, "tags": a["tag"], "featured_media": mid}
    st, p = rest("/wp-json/wp/v2/posts", "POST", payload)
    if st not in (201, 200):
        print(f"  GAGAL buat artikel: {st} {str(p)[:200]}")
        continue
    pid = p["id"]
    print(f"  artikel #{pid} dibuat (draft) → {p.get('link')}")
    hasil.append((a, pid, mid))

print("\n=== META YOAST (XML-RPC) ===")
for a, pid, mid in hasil:
    st, isi = rpc("wp.editPost", [1, USER, PASS, pid, {"custom_fields": [
        {"key": "_yoast_wpseo_focuskw", "value": a["fokus"]},
        {"key": "_yoast_wpseo_title", "value": a["seo"]},
        {"key": "_yoast_wpseo_metadesc", "value": a["meta"]}]}])
    print(f"  #{pid} {a['slug']:<38} HTTP {st} | {'tersimpan' if '<boolean>1</boolean>' in isi else '❌ ' + isi[:120]}")

print("\n=== VERIFIKASI (baca ulang) ===")
for a, pid, mid in hasil:
    st, c = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,categories,tags,featured_media,status,link")
    raw = c.get("content", {}).get("raw", "") if isinstance(c, dict) else ""
    teks = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", raw, flags=re.S | re.I)
    kata = len([w for w in re.split(r"\s+", re.sub(r"<[^>]+>", " ", teks)) if w])
    punya_home = "https://www.tslaw.id/" in raw
    print(f"  #{pid} {a['slug']:<38} {len(raw):>6} char | {kata:>5} kata | kat {c.get('categories')} | "
          f"tag {len(c.get('tags', []))} | foto {c.get('featured_media')}")
    print(f"       tombol WA: {'ada' if 'wa.me' in raw else 'TIDAK'} | schema FAQ: {'ada' if 'FAQPage' in raw else 'TIDAK'} | "
          f"link ke beranda: {'ADA' if punya_home else 'TIDAK'} | status {c.get('status')}")
