#!/usr/bin/env python3
"""Verifikasi akhir: berapa artikel StudioSoft yang punya tombol WhatsApp, dan mana yang belum."""
import base64, json, time, urllib.request, urllib.error

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()


def api(path, data=None):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(S + path, data=body, headers=h, method="POST" if data else "GET")
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=200) as x:
                return x.status, json.loads(x.read())
        except Exception as e:
            time.sleep(3)
            err = e
    return 0, str(err)[:120]


posts, page = [], 1
while True:
    st, d = api(f"/wp-json/wp/v2/posts?per_page=100&page={page}&context=edit&_fields=id,title,link,content")
    if not isinstance(d, list):
        print("gagal halaman", page, str(d)[:100]); break
    posts += d
    if len(d) < 100:
        break
    page += 1

punya = [p for p in posts if isinstance(p["content"], dict) and "ss-cta-wa" in p["content"]["raw"]]
belum = [p for p in posts if isinstance(p["content"], dict) and "ss-cta-wa" not in p["content"]["raw"]]
print(f"total artikel publish : {len(posts)}")
print(f"punya tombol WA       : {len(punya)}")
print(f"BELUM punya tombol    : {len(belum)}")
for p in belum:
    print(f"   #{p['id']} {p['title']['rendered'][:66]}")

# cek versi live beberapa halaman (tanpa pembeda cache? pakai pembeda supaya fresh)
print("\n=== cek live (3 sampel) ===")
for p in (punya[:1] + punya[len(punya)//2:len(punya)//2 + 1] + punya[-1:]):
    try:
        r = urllib.request.Request(p["link"] + "?nc=" + str(int(time.time())), headers={"User-Agent": "Mozilla/5.0"})
        h = urllib.request.urlopen(r, timeout=90).read().decode("utf-8", "replace")
        print(f"  tombol:{'ADA' if 'ss-cta-wa' in h else 'TIDAK'} | warna:{'#6878d6' in h} | wa.me:{'6281935000624' in h} | {p['link'].replace(S,'')[:52]}")
    except Exception as e:
        print("  gagal cek", p["link"][:50], str(e)[:60])
