#!/usr/bin/env python3
"""Yasma: link internal klaster maklon → halaman payung #2729 + cari & perbaiki halaman CTR rendah."""
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()
PAYUNG = "https://yasmanatura.co.id/jasa-maklon-minuman-herbal/"
ANCHOR = "jasa maklon herbal Sidoarjo"

KANDIDAT = [2899, 3424, 3279, 3146, 3149, 3152, 2864, 2868, 2907, 3129, 3133, 3440, 3246]


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=200) 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. Link dari klaster maklon → halaman payung ===")
ok = lewat = 0
for pid in KANDIDAT:
    st, p = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=type,content,title,status")
    if not isinstance(p, dict) or p.get("type") != "post" or p.get("status") != "publish":
        print(f"  #{pid} dilewati (tipe={p.get('type') if isinstance(p,dict) else st} status={p.get('status') if isinstance(p,dict) else '-'})")
        lewat += 1
        continue
    raw = p["content"]["raw"]
    if PAYUNG in raw:
        print(f"  #{pid} sudah menautkan"); lewat += 1; continue
    blok = (f'\n<h2>Baca juga</h2>\n<p>Panduan lengkap alur produksinya ada di '
            f'<a href="{PAYUNG}">{ANCHOR}</a> — dari formulasi, bahan baku, kemasan, sampai legalitas.</p>\n')
    m = re.search(r"\n<h2[^>]*>\s*(Pertanyaan|FAQ|Kesimpulan|Baca juga|Penutup)", raw, re.I)
    baru = (raw[:m.start()] + blok + raw[m.start():]) if m else (raw.rstrip() + "\n" + blok)
    st2, _ = api(f"/wp-json/wp/v2/posts/{pid}", {"content": baru})
    _, chk = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    jadi = PAYUNG in chk.get("content", {}).get("raw", "")
    print(f"  #{pid} POST {st2} | {'masuk' if jadi else 'GAGAL'} | {html.unescape(p['title']['rendered'])[:46]}")
    ok += 1 if jadi else 0
print(f"\n  ringkas: {ok} ditautkan | {lewat} dilewati")

print("\n=== 2. Cari halaman '/7-alasan-yasma-natura...' (CTR 0,3%) ===")
st, d = api("/wp-json/wp/v2/posts?search=7%20Alasan%20Yasma&per_page=5&context=edit&_fields=id,slug,type,title,meta,link")
if isinstance(d, list):
    for p in d:
        m = p.get("meta", {})
        print(f"  #{p['id']} tipe={p.get('type')} | {p['slug'][:60]}")
        print(f"     fk: {m.get('_yoast_wpseo_focuskw','')} | meta {len(m.get('_yoast_wpseo_metadesc','') or '')} char")
        print(f"     SEO title: {(m.get('_yoast_wpseo_title') or '(default)')[:70]}")
