#!/usr/bin/env python3
"""Perbaiki meta halaman /practice-areas/: hapus noindex, sisakan canonical ke /layanan/ saja."""
import re, time, urllib.request
import xmlrpc.client

SITUS = "https://www.tslaw.id"
USER, SANDI = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
PID = 3727
TUJUAN = "https://www.tslaw.id/layanan/"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0"}
HAPUS = ("_yoast_wpseo_canonical", "_yoast_wpseo_meta-robots-noindex")

p = xmlrpc.client.ServerProxy(f"{SITUS}/xmlrpc.php", allow_none=True)
post = p.wp.getPost(0, USER, SANDI, PID)
lama = post.get("custom_fields", [])
print(f"sebelum: {len(lama)} custom field")
for cf in lama:
    if any(h in cf.get("key", "") for h in HAPUS):
        print(f"   {cf['key']} = {cf['value']}")

baru = [cf for cf in lama if not any(h in cf.get("key", "") for h in HAPUS)]
baru.append({"key": "_yoast_wpseo_canonical", "value": TUJUAN})
print(f"\nsesudah disusun: {len(baru)} custom field (canonical saja, tanpa noindex)")
p.wp.editPost(0, USER, SANDI, PID, {"custom_fields": baru})
time.sleep(3)

cek = p.wp.getPost(0, USER, SANDI, PID)
print("\nterbaca kembali:")
for cf in cek.get("custom_fields", []):
    if any(k in cf.get("key", "") for k in HAPUS):
        print(f"   {cf['key']} = {cf['value']}")

print("\nhalaman live (dengan penghindar cache):")
for suffix in ("", "?nocache=1", "?v=" + str(int(time.time()))):
    try:
        t = urllib.request.urlopen(urllib.request.Request(f"{SITUS}/practice-areas/{suffix}", headers=UA), timeout=45).read().decode("utf-8", "replace")
        canon = re.search(r'rel=["\']canonical["\'][^>]*href=["\']([^"\']+)["\']', t, re.I)
        robots = re.search(r'name=["\']robots["\'] content=["\']([^"\']*)["\']', t, re.I)
        print(f"   {suffix or '(polos)'}: canonical {canon.group(1) if canon else '-'} · robots {robots.group(1) if robots else '-'}")
    except Exception as e:
        print(f"   {suffix}: gagal {str(e)[:40]}")
    time.sleep(1)
