#!/usr/bin/env python3
"""Yasma: perbaiki #2793 (CTR 0,3% di 3.551 impresi) — arahkan ke kata kunci topiknya + tautkan ke payung."""
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/"
PID = 2793
FK = "jasa produksi minuman serbuk"
SEO_TITLE = "Jasa Produksi Minuman Serbuk: 7 Hal yang Perlu Dicek"
META = ("Jasa produksi minuman serbuk untuk brand baru: 7 hal yang perlu dicek sebelum memilih penyedia, "
        "dari bahan baku sampai legalitas dan jumlah produksi.")


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"


st, p = api(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=type,content,title")
print(f"GUARD: #{PID} tipe={p.get('type')}")
if p.get("type") != "post":
    print("⛔ bukan post — dibatalkan"); raise SystemExit(1)
print(f"judul: {p['title']['rendered'][:70]}")
print(f"meta baru {len(META)} char | fk di awal: {META.lower().startswith(FK.lower())}")

st1, _ = api(f"/wp-json/wp/v2/posts/{PID}", {
    "meta": {"_yoast_wpseo_focuskw": FK, "_yoast_wpseo_title": SEO_TITLE, "_yoast_wpseo_metadesc": META}})

raw = p["content"]["raw"]
if PAYUNG not in raw:
    blok = (f'\n<h2>Baca juga</h2>\n<p>Alur produksinya dibahas lengkap di '
            f'<a href="{PAYUNG}">jasa maklon herbal Sidoarjo</a> — formulasi, bahan baku, kemasan, dan legalitas.</p>\n')
    m = re.search(r"\n<h2[^>]*>\s*(Pertanyaan|FAQ|Kesimpulan|Baca juga)", 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})
    print(f"link ke payung: POST {st2}")

_, chk = api(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=meta,content")
print(f"\nverifikasi: fk='{chk['meta'].get('_yoast_wpseo_focuskw')}' | meta {len(chk['meta'].get('_yoast_wpseo_metadesc',''))} char | "
      f"link payung {'ada' if PAYUNG in chk['content']['raw'] else 'tidak'}")
