#!/usr/bin/env python3
"""Fase 1 item 4 — pasang judul + meta Yoast ke 10 artikel nol klik.
Pakai `--go` untuk menulis. Default: dry run + pemeriksaan panjang/CJK.
"""
import base64, html, json, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
UA = {"User-Agent": "Mozilla/5.0"}
RENCANA = f"{WS}/drafts/ss_fase1_meta_rencana.json"
LOG = f"{WS}/drafts/ss_fase1_meta_log.json"
CJK = re.compile(r"[\u3000-\u9fff\uff00-\uffef\uac00-\ud7af]")


def rest(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(S + 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"


def halaman(slug):
    """baca judul + meta description dari halaman live"""
    r = urllib.request.Request(f"{S}/{slug}/", headers=UA)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            t = x.read().decode("utf-8", "replace")
        judul = re.search(r"<title>(.*?)</title>", t, re.S)
        desc = re.search(r'<meta name="description" content="([^"]*)"', t)
        og = re.search(r'<meta property="og:title" content="([^"]*)"', t)
        return {"judul_live": html.unescape(judul.group(1).strip()) if judul else None,
                "desc_live": html.unescape(desc.group(1).strip()) if desc else None,
                "og_judul": html.unescape(og.group(1).strip()) if og else None}
    except Exception as e:
        return {"err": str(e)[:90]}


renc = json.load(open(RENCANA))["items"]
print("=== pemeriksaan ===")
masalah = []
for x in renc:
    jl, dl = len(x["yoast_judul"]), len(x["yoast_desc"])
    tanda = []
    if jl > 60:
        tanda.append(f"judul {jl} char (>60)")
    if not 120 <= dl <= 158:
        tanda.append(f"desc {dl} char (luar 120-158)")
    if CJK.search(x["yoast_judul"] + x["yoast_desc"] + x["judul_baru"]):
        tanda.append("CJK!")
    if "—" in x["yoast_judul"] + x["yoast_desc"]:
        tanda.append("em dash")
    print(f"  #{x['id']:>5} judul {jl:>2} · desc {dl:>3} · " + ("OK" if not tanda else " ⚠ " + ", ".join(tanda)))
    if tanda:
        masalah.append(x["id"])
print(f"\n  {len(renc)} artikel diperiksa, {len(masalah)} perlu dicek ulang: {masalah}")

if "--go" not in sys.argv:
    print("\n(dry run — pakai --go)")
    sys.exit(0)

log = []
for x in renc:
    st, d = rest(f"/wp-json/wp/v2/posts/{x['id']}", "POST", {
        "title": x["judul_baru"],
        "meta": {"_yoast_wpseo_title": x["yoast_judul"], "_yoast_wpseo_metadesc": x["yoast_desc"],
                 "_yoast_wpseo_focuskw": x["fokus"]}})
    if not isinstance(d, dict) or "id" not in d:
        print(f"  #{x['id']} ❌ HTTP {st} {str(d)[:120]}")
        log.append({"id": x["id"], "ok": False, "err": f"{st} {str(d)[:120]}"})
        continue
    slug = d.get("slug")
    m = (d.get("meta") or {})
    time.sleep(2)
    live = halaman(slug)
    cocok = (live.get("judul_live") == x["yoast_judul"] and live.get("desc_live") == x["yoast_desc"])
    print(f"  #{x['id']:>5} HTTP {st} | judul tersimpan: {'ya' if m.get('_yoast_wpseo_title') == x['yoast_judul'] else 'TIDAK'}"
          f" | live: {'cocok ✅' if cocok else 'BELUM cocok'}")
    if not cocok:
        print(f"        live → {str(live.get('judul_live'))[:80]}")
    log.append({"id": x["id"], "slug": slug, "ok": bool(cocok), "judul_baru": x["judul_baru"],
                "yoast_judul": x["yoast_judul"], "yoast_desc": x["yoast_desc"],
                "live_judul": live.get("judul_live"), "live_desc": live.get("desc_live")})

json.dump(log, open(LOG, "w"), ensure_ascii=False, indent=1)
ok = sum(1 for l in log if l["ok"])
print(f"\n  berhasil cocok di halaman live: {ok}/{len(log)}  → {LOG}")
