#!/usr/bin/env python3
"""DAS: lacak artikel yang memakai nomor WA salah + yang belum punya tombol AMBIL PROMO."""
import base64, html, json, os, re, time, urllib.request, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
BENAR = "6285242380789"
SALAH = {"6281935000624": "nomor StudioSoft", "6281909222026": "nomor TSLaw",
         "6285242430789": "angka tertukar (4238 → 4243)"}


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return []


posts, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,title,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1
print(f"artikel: {len(posts)}\n")

print("=== A. artikel dengan nomor WA SALAH ===")
for p in posts:
    raw = p.get("content", {}).get("raw", "") or ""
    for no, ket in SALAH.items():
        if no in raw:
            print(f"   #{p['id']:>5} [{ket}] /{p['slug'][:44]}")
            mm = re.search(r".{0,120}" + no + r".{0,120}", raw, re.S)
            if mm:
                print(f"        …{re.sub(chr(10), ' ', mm.group(0))[:230]}…")

print("\n=== B. artikel tanpa tombol AMBIL PROMO (daftar lengkap) ===")
tanpa = [p for p in posts if not re.search(r"AMBIL\s*PROMO", p.get("content", {}).get("raw", "") or "", re.I)]
for p in tanpa:
    raw = p.get("content", {}).get("raw", "") or ""
    ada_wa = "wa.me" in raw or "api.whatsapp" in raw
    print(f"   #{p['id']:>5} {'ada WA biasa' if ada_wa else 'TANPA WA sama sekali':<20} {html.unescape(p['title']['rendered'])[:54]}")
print(f"   total: {len(tanpa)}")
