#!/usr/bin/env python3
"""Publish 2 artikel EveryBe: Co Bloong & Feminine V Spray."""
import base64, json, re, requests

WP = "https://www.everybeofficial.com/wp-json/wp/v2"
USER = "bambangbot"
APP_PASS = "2Aa0 OwYY NJaL Oc8b 9OCo Owcw"
AUTH = base64.b64encode(f"{USER}:{APP_PASS}".encode()).decode()
HDR = {"Authorization": f"Basic {AUTH}", "Content-Type": "application/json"}

# ---- baca draf ----
def read(path):
    with open(path, encoding="utf-8") as f:
        return f.read().strip()

def md_to_html(md):
    """Konversi markdown sederhana (## / ### / paragraf / blockquote / bold) ke HTML, tanpa H1."""
    lines = md.split("\n")
    out = []
    in_list = False
    for line in lines:
        s = line.strip()
        if not s:
            if in_list:
                out.append("</ul>")
                in_list = False
            continue
        # heading
        m = re.match(r'^(#{2,3})\s+(.*)$', s)
        if m:
            if in_list:
                out.append("</ul>"); in_list = False
            lvl = len(m.group(1))
            out.append(f"<h{lvl}>{m.group(2)}</h{lvl}>")
            continue
        # list item
        m = re.match(r'^\d+\.\s+(.*)$', s)
        if m:
            if not in_list:
                out.append("<ul>"); in_list = True
            out.append(f"<li>{m.group(1)}</li>")
            continue
        m = re.match(r'^-\s+(.*)$', s)
        if m:
            if not in_list:
                out.append("<ul>"); in_list = True
            out.append(f"<li>{m.group(1)}</li>")
            continue
        # blockquote
        if s.startswith(">"):
            if in_list:
                out.append("</ul>"); in_list = False
            out.append(f"<blockquote>{s.lstrip('> ')}</blockquote>")
            continue
        # paragraph
        if in_list:
            out.append("</ul>"); in_list = False
        # bold **text**
        s = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', s)
        out.append(f"<p>{s}</p>")
    if in_list:
        out.append("</ul>")
    return "\n".join(out)

def wc(html):
    txt = re.sub(r'<[^>]+>', ' ', html)
    return len([w for w in re.split(r'\s+', txt) if re.search(r'[A-Za-z0-9]', w)])

articles = [
    {
        "title": "Co Bloong: Solusi Praktis untuk Pegal dan Otot Kaku",
        "slug": "co-bloong-solusi-praktis-pegal-otot-kaku",
        "excerpt": "Pegal dan otot kaku sering mengganggu aktivitas. Kenali penyebab, tips pijat yang benar, dan manfaat Co Bloong dari EveryBe untuk menjaga otot dan sendi tetap nyaman.",
        "md": "/home/mantapman/.openclaw/workspace-ujang/artikel_everybe_cobloong.md",
        "cats": [],
    },
    {
        "title": "Pentingnya Menjaga Kebersihan Kewanitaan Setiap Hari",
        "slug": "pentingnya-menjaga-kebersihan-kewanitaan-setiap-hari",
        "excerpt": "Jaga kebersihan dan kenyamanan area kewanitaan dengan cara yang benar. Pelajari tips harian dan manfaat Feminine V Spray dari EveryBe untuk wanita aktif.",
        "md": "/home/mantapman/.openclaw/workspace-ujang/artikel_everybe_femine.md",
        "cats": [],
    },
]

for a in articles:
    content = md_to_html(read(a["md"]))
    payload = {
        "title": a["title"],
        "slug": a["slug"],
        "excerpt": a["excerpt"],
        "content": content,
        "status": "publish",
        "meta": {},
    }
    if a["cats"]:
        payload["categories"] = a["cats"]
    r = requests.post(f"{WP}/posts", headers=HDR, json=payload, timeout=60)
    print("=" * 60)
    print("TITLE:", a["title"])
    print("SLUG :", a["slug"])
    print("WORDS:", wc(content))
    if r.status_code in (200, 201):
        d = r.json()
        print("POST ID:", d.get("id"))
        print("LINK  :", d.get("link"))
    else:
        print("STATUS:", r.status_code)
        print(r.text[:500])
