#!/usr/bin/env python3
"""TSLaw: bereskan (1) halaman sampah, (2) zona waktu; lalu tampilkan judul/meta sasaran
yang berimpresi tapi nol klik, supaya bisa diperbaiki di langkah berikutnya."""
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 wp(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=120) 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("=== A. halaman sampah ===")
st, d = wp("/wp-json/wp/v2/pages/2?_fields=id,title,slug,status,link")
print(f"   Sample Page: HTTP {st} | {d}")
st, _ = wp("/wp-json/wp/v2/pages/2", "DELETE")
print(f"   → pindah ke Trash: HTTP {st}")
st, cek = wp("/wp-json/wp/v2/pages/2?_fields=id,status")
print(f"   → verifikasi: {cek}")

print("\n=== B. cek URL sisa (hello-world, ?p=1) ===")
for u in ("/hello-world/", "/?p=1", "/sample-page/"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}{u}", headers=UA), timeout=45)
        isi = r.read().decode("utf-8", "replace")
        t = re.search(r"<title>(.*?)</title>", isi, re.S)
        print(f"   {r.status} | {u:<16} judul: {html.unescape(t.group(1))[:60] if t else '-'}")
    except urllib.error.HTTPError as e:
        print(f"   {e.code} | {u}")

print("\n=== C. zona waktu ===")
st, s = wp("/wp-json/wp/v2/settings")
print(f"   sebelum: timezone='{s.get('timezone') if isinstance(s, dict) else s}'")
st, s2 = wp("/wp-json/wp/v2/settings", "POST", {"timezone": "Asia/Jakarta"})
print(f"   POST: HTTP {st}")
st, s3 = wp("/wp-json/wp/v2/settings")
print(f"   sesudah: timezone='{s3.get('timezone') if isinstance(s3, dict) else s3}'")

print("\n=== D. sasaran perbaikan cuplikan (berimpresi, nol klik) ===")
SASARAN = [
    ("pages", 834, "/tentang/", 85, 0, 6.7),
    ("pages", 12, "/practice-areas/", 120, 1, 14.1),
    ("posts", None, "cara-daftar-merek-dagang", 52, 0, 45.3),
    ("posts", None, "cara-lapor-polisi-penipuan-online", 49, 0, 28.7),
    ("posts", None, "6-langkah-mengurus-sengketa-tanah", 39, 0, 7.7),
]
for tipe, pid, kunci, imp, klik, pos in SASARAN:
    if pid:
        st, p = wp(f"/wp-json/wp/v2/{tipe}/{pid}?context=edit&_fields=id,title,link,meta")
    else:
        st, lst = wp(f"/wp-json/wp/v2/{tipe}?search={kunci.replace('-', '+')}&per_page=3&context=edit&_fields=id,title,link,meta")
        p = lst[0] if isinstance(lst, list) and lst else None
    if not p:
        print(f"   ({kunci}) tidak ditemukan")
        continue
    print(f"\n   #{p['id']} imp {imp} klik {klik} pos {pos}  {p['link']}")
    print(f"      judul SEO : {p['meta'].get('_yoast_wpseo_title') or '(kosong, pakai judul artikel)'}")
    print(f"      meta desc : ({len(p['meta'].get('_yoast_wpseo_metadesc') or '')} char) {p['meta'].get('_yoast_wpseo_metadesc') or '(KOSONG)'}")
    print(f"      fokus kw  : {p['meta'].get('_yoast_wpseo_focuskw') or '(kosong)'}")
    print(f"      judul     : {html.unescape(p['title']['rendered'])[:80]}")
print("\n   (meta Yoast bisa ditulis lewat REST:", "YA" if isinstance(s3, dict) else "belum dipastikan", ")")
