#!/usr/bin/env python3
"""Perbaiki tautan ke pilar #3475 (pakai URL kanonik) + cek status URL yang dipensiunkan."""
import base64, html, json, re, time, urllib.request, urllib.error

S = "https://yasmanatura.co.id"
AUTH = base64.b64encode(b"bambangbot:LFp4 LXBh kMYG 84qC 2DDc 5bLc").decode()
PILAR_LAMA = "https://yasmanatura.co.id/maklon-minuman-serbuk-indonesia-yasma-natura-partner/"
PILAR_BARU = "https://yasmanatura.co.id/maklon-minuman-serbuk-indonesia-yasma-natura-partner-maklon-nasional-untuk-produk-minuman-kesehatan/"
TAUT = [4232, 2779, 3333, 3420, 3477]


def api(path, data=None, method=None):
    method = method or ("POST" if data is not None else "GET")
    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"
    err = None
    r = urllib.request.Request(S + path, data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=220) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (404, 410, 500, 502, 503, 504):
                time.sleep(4); continue
            return e.code, e.read().decode()[:200]
        except Exception as e:
            err = e; time.sleep(4)
    return 0, str(err)[:150] if err else "gagal"


print("=== 1. Ganti tautan ke URL kanonik pilar ===")
for pid in TAUT:
    st, p = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content,type")
    if p.get("type") != "post":
        print(f"  #{pid} bukan post — dilewati"); continue
    raw = p["content"]["raw"]
    if PILAR_LAMA not in raw and PILAR_BARU not in raw:
        print(f"  #{pid} tidak menautkan pilar — dilewati"); continue
    baru = raw.replace(PILAR_LAMA, PILAR_BARU)
    if baru == raw:
        print(f"  #{pid} sudah pakai URL kanonik"); continue
    st2, _ = api(f"/wp-json/wp/v2/posts/{pid}", {"content": baru})
    _, chk = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    r2 = chk["content"]["raw"]
    print(f"  #{pid} POST {st2} | kanonik: {'YA' if PILAR_BARU in r2 else 'TIDAK'} | sisa URL pendek: {'masih ada' if PILAR_LAMA in r2 else 'bersih'}")

print("\n=== 2. Cek URL yang dipensiunkan (dengan pembeda cache) ===")
import urllib.request as ur
for u in ("/proses-produksi-maklon-minuman-serbuk/", "/jasa-maklon-minuman-serbuk-alami-terpercaya-produksi/",
          "/yasma-natura-maklon-minuman-serbuk-herbal/"):
    for label, q in (("tanpa cache-buster", ""), ("cache-buster", "?nc=%d" % int(time.time()))):
        try:
            r = ur.Request(S + u + q, headers={"User-Agent": "Mozilla/5.0"})
            resp = ur.urlopen(r, timeout=60)
            print(f"  {resp.status} | cf={resp.headers.get('cf-cache-status','-')} | {label} | {u}")
        except urllib.error.HTTPError as e:
            print(f"  {e.code} | {label} | {u}")
        except Exception as e:
            print(f"  ERR {str(e)[:40]} | {label} | {u}")
