#!/usr/bin/env python3
"""TSLaw: terbitkan dua listikel lalu verifikasi di halaman live."""
import base64, html, json, re, time, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


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 _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("=== TERBITKAN ===")
for pid in (3454, 3456):
    st, p = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"status": "publish"})
    print(f"  #{pid} → HTTP {st} | status {p.get('status') if isinstance(p, dict) else p} | {p.get('link') if isinstance(p, dict) else ''}")
    time.sleep(2)

print("\n=== VERIFIKASI HALAMAN LIVE ===")
for pid in (3454, 3456):
    st, p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=link,title,status")
    url = p.get("link")
    h = urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120).read().decode("utf-8", "replace")
    t = re.search(r"<title>(.*?)</title>", h, re.S)
    teks = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", h, flags=re.S | re.I))))
    h3 = [html.unescape(re.sub(r"<[^>]+>", "", x))[:44] for x in re.findall(r"<h3[^>]*>(.*?)</h3>", h, re.S)]
    print(f"\n  #{pid} {url}")
    print(f"     judul live : {t.group(1) if t else '-'}")
    print(f"     kata       : {len(teks.split())} | gambar: {len(re.findall(r'<img', h))}")
    print(f"     entri (h3) : {h3[:4]}")
    print(f"     no.1 = Tito Suprianto Law Firm: {'YA' if 'Tito Suprianto Law Firm' in h[:40000] else 'periksa'}")
    ada_home = re.search(r'href="https://www[.]tslaw[.]id/"', h)
    print(f"     link ke beranda: {'ADA' if ada_home else 'TIDAK'}")
    print(f"     tombol WA  : {'ada' if 'wa.me' in h else 'TIDAK'} | schema FAQ: {'ada' if 'FAQPage' in h else 'TIDAK'}")
    md = re.search(r'<meta name="description" content="([^"]*)"', h)
    print(f"     meta desc  : {len(md.group(1)) if md else 0} char")
    link_int = sorted(set(re.findall(r'href="https://www[.]tslaw[.]id(/[^"]*)"', h)))
    print(f"     link internal lain: {link_int[:6]}")

print("\n=== daftar artikel terbaru ===")
st, d = rest("/wp-json/wp/v2/posts?per_page=4&_fields=id,title,link,status,date")
for x in d if isinstance(d, list) else []:
    print(f"  #{x['id']} [{x['status']}] {x['date'][:10]} {html.unescape(x['title']['rendered'])[:60]}")
