#!/usr/bin/env python3
"""Cek tombol WhatsApp di semua artikel TSC (terbit + terjadwal) dan pasang yang belum ada.

Pakai --go untuk memasang tombol yang hilang.
"""
import base64, importlib.util, json, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}

WA = ("https://wa.me/6285117444417?text=Saya%20ingin%20konsultasi%20masalah%20kulit%20di%20"
      "The%20Skin%20Code%20Clinic")
TOMBOL = ('<p style="text-align:center;margin:32px 0 8px"><a class="wp-block-button__link '
          'wp-element-button" href="' + WA + '" target="_blank" rel="noopener" '
          'style="display:inline-block;background-color:#0f2557;color:#ffffff;padding:15px 34px;'
          'font-size:18px;font-weight:bold;text-decoration:none;border-radius:6px;">KONSULTASI GRATIS'
          '</a></p>')


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 i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=150) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4 * (i + 1))
                continue
            return e.code, e.read().decode()[:160]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def tombol_ada(raw):
    return bool(re.search(r"wa\.me/|api\.whatsapp\.com", raw))


print("=== artikel TSC: punya tombol WhatsApp? ===")
hasil = {"punya": [], "tidak": []}
for status in ("publish", "future"):
    page = 1
    while True:
        st, d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status={status}&context=edit"
                     f"&_fields=id,slug,link,date,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            raw = x["content"]["raw"]
            (hasil["punya"] if tombol_ada(raw) else hasil["tidak"]).append(
                {"id": x["id"], "slug": x["slug"], "status": status, "date": x["date"][:10],
                 "panjang": len(raw)})
        if len(d) < 100:
            break
        page += 1
        time.sleep(0.4)

print(f"   punya tombol: {len(hasil['punya'])}")
print(f"   BELUM punya : {len(hasil['tidak'])}")
for x in hasil["tidak"][:15]:
    print(f"      #{x['id']:<6} {x['status']:<8} {x['date']} | /{x['slug'][:56]}")

json.dump(hasil, open(f"{WS}/drafts/tsc_tombol_wa.json", "w"), ensure_ascii=False, indent=1)

if "--go" not in sys.argv:
    print("\n(dry run — pakai --go untuk memasang tombol yang hilang)")
    sys.exit(0)

print("\n=== memasang tombol ===")
ok = gagal = 0
for x in hasil["tidak"]:
    st, o = rest(f"/wp-json/wp/v2/posts/{x['id']}?context=edit&_fields=content")
    if not isinstance(o, dict) or "content" not in o:
        print(f"   #{x['id']} gagal baca")
        gagal += 1
        continue
    raw = o["content"]["raw"]
    baru = raw.rstrip() + "\n" + TOMBOL + "\n"
    st2, _ = rest(f"/wp-json/wp/v2/posts/{x['id']}", "POST", {"content": baru})
    time.sleep(1)
    _, cek = rest(f"/wp-json/wp/v2/posts/{x['id']}?context=edit&_fields=content")
    sukses = isinstance(cek, dict) and tombol_ada(cek.get("content", {}).get("raw", ""))
    print(f"   {'✅' if sukses else '❌'} #{x['id']:<6} {x['status']:<8} HTTP {st2} | /{x['slug'][:48]}")
    ok += sukses
    gagal += (not sukses)
    time.sleep(0.6)
print(f"\n   berhasil: {ok} · gagal: {gagal}")
