# -*- coding: utf-8 -*-
"""
Publisher 6 artikel listikel RSIA Kendangsari ke WordPress.
Alur:
1. Baca metadata (meta_6listikel.py) + konten (konten_1_2 / konten_3_4 / konten_5_6)
2. Cari & download gambar Pexels sesuai query -> konversi WebP (WAJIB WebP)
3. Upload featured image ke WP -> buat tag baru (jika belum ada) -> post artikel
   (kategori Edukasi 47, tags, Yoast meta desc & focus kw) -> set featured image
4. Verifikasi & lapor URL
"""
import sys, os, re, io, json, time, base64
import urllib.request

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from meta_6listikel import ARTIKEL
from pexels_image import cari_gambar_pexels, download_gambar

WP_URL = "https://rsia.kendangsari.com/wp-json/wp/v2"
WP_USER = "bambangbot"
WP_PASS = "INJ6 7ag4 iouR Fqkm 4alp Dkng"
KATEGORI_EDUKASI = 47

KONTEN_SOURCES = {
    1: "konten_1_2.py",
    2: "konten_1_2.py",
    3: "konten_3_4.py",
    4: "konten_3_4.py",
    5: "konten_5_6.py",
    6: "konten_5_6.py",
}

def load_article_content(art_no):
    src = KONTEN_SOURCES.get(art_no)
    if not src:
        return None
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), src)
    if not os.path.exists(path):
        return None
    import importlib.util
    spec = importlib.util.spec_from_file_location(src.replace('.py', ''), path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return getattr(mod, f"KONTEN_{art_no}", None)

def word_count(html):
    txt = re.sub(r'<[^>]+>', ' ', html)
    return len([w for w in txt.split() if re.search(r'[a-zA-Z0-9]', w)])

UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'


def http_json(method, url, data=None, token=None):
    req = urllib.request.Request(url, method=method)
    req.add_header('Content-Type', 'application/json')
    req.add_header('User-Agent', UA)
    if token:
        req.add_header('Authorization', 'Basic ' + token)
    body = json.dumps(data).encode() if data is not None else None
    try:
        with urllib.request.urlopen(req, data=body, timeout=90) as r:
            return r.status, json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode())
        except Exception:
            return e.code, {}

def get_or_create_tag(name, token):
    """Cari tag by nama; buat baru jika belum ada. Return tag id atau None."""
    st, j = http_json('GET', WP_URL + f"/tags?search={urllib.parse.quote(name)}", token=token)
    if st == 200 and j:
        for t in j:
            if t.get('name', '').lower() == name.lower():
                return t.get('id')
    st, j = http_json('POST', WP_URL + '/tags', {"name": name}, token)
    if st in (200, 201):
        return j.get('id')
    return None

def upload_image_webp(img_bytes, alt, token):
    """Upload WebP ke media WP. Return media id atau None."""
    fname = f"rsia-{int(time.time())}.webp"
    up = WP_URL + '/media'
    req = urllib.request.Request(up, data=img_bytes, method='POST')
    req.add_header('Content-Type', 'image/webp')
    req.add_header('Content-Disposition', f'attachment; filename="{fname}"')
    req.add_header('Authorization', 'Basic ' + token)
    req.add_header('User-Agent', UA)
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            j = json.loads(r.read().decode())
            return j.get('id')
    except urllib.error.HTTPError as e:
        try:
            return json.loads(e.read().decode()).get('id')
        except Exception:
            return None

def buat_webp(data, size=(1200, 630)):
    """Konversi bytes gambar -> bytes WebP 1200x630 center-crop, quality 90."""
    from PIL import Image
    im = Image.open(io.BytesIO(data)).convert("RGB")
    tw, th = size
    w, h = im.size
    target = tw / th
    curr = w / h
    if curr > target:
        nw = int(h * target)
        left = (w - nw) // 2
        im = im.crop((left, 0, left + nw, h))
    else:
        nh = int(w / target)
        top = (h - nh) // 2
        im = im.crop((0, top, w, top + nh))
    im = im.resize(size, Image.LANCZOS)
    buf = io.BytesIO()
    im.save(buf, "WEBP", quality=90)
    return buf.getvalue()

def main():
    import urllib.parse
    token = base64.b64encode(f"{WP_USER}:{WP_PASS}".encode()).decode()
    results = []
    for a in ARTIKEL:
        no = a['no']
        konten = load_article_content(no)
        if not konten:
            results.append((no, 'SKIP', 'konten tidak ditemukan'))
            continue
        wc = word_count(konten)
        if wc < 1300:
            results.append((no, 'SKIP-KURANG', f'{wc} kata (<1300)'))
            continue

        # 1. Cari & proses gambar (WebP)
        judul_untuk_query = f"{a['judul']} {a.get('gambar_query', '')}"
        photo = cari_gambar_pexels(judul_untuk_query, web="rsia_kendangsari", orientasi="landscape")
        if not photo:
            results.append((no, 'SKIP', 'gambar Pexels tidak ditemukan'))
            continue
        data = download_gambar(photo["url"])
        if not data:
            results.append((no, 'SKIP', 'download gambar gagal'))
            continue
        webp_bytes = buat_webp(data.read() if hasattr(data, 'read') else data)
        media_id = upload_image_webp(webp_bytes, a['alt'], token)
        if not media_id:
            results.append((no, 'SKIP', 'upload gambar gagal'))
            continue
        print(f'  ✅ Gambar WebP terupload (media {media_id})', flush=True)

        # 2. Siapkan tags (existing + baru)
        tag_ids = list(a.get('tags', []))
        for tn in a.get('new_tags', []):
            tid = get_or_create_tag(tn, token)
            if tid:
                tag_ids.append(tid)
                print(f'  ✅ Tag "{tn}" -> {tid}', flush=True)
            else:
                print(f'  ⚠️ Tag "{tn}" gagal dibuat', flush=True)

        # 3. Buat post
        payload = {
            "title": a['judul'],
            "content": konten,
            "slug": a['slug'],
            "status": "publish",
            "categories": [KATEGORI_EDUKASI],
            "tags": tag_ids,
            "excerpt": a['meta_desc'],
            "comment_status": "open",
            "ping_status": "open",
            "meta": {
                "_yoast_wpseo_metadesc": a['meta_desc'],
                "_yoast_wpseo_focuskw": a['keyphrase'],
                "_yoast_wpseo_title": a['judul'],
            },
        }
        st, j = http_json('POST', WP_URL + '/posts', payload, token)
        if st not in (200, 201):
            results.append((no, 'FAIL-POST', str(j)[:200]))
            continue
        post_id = j.get('id')
        link = j.get('link')

        # 4. Set featured image
        if post_id:
            st2, j2 = http_json('POST', f"{WP_URL}/posts/{post_id}", {"featured_media": media_id}, token)
        results.append((no, 'OK', f'id={post_id} {wc} kata link={link}'))
        print(f'[DONE] #{no} {a["slug"]} -> {link}', flush=True)
        time.sleep(1)

    print('\n===== RINGKASAN =====')
    for r in results:
        print(r)

if __name__ == '__main__':
    main()
