#!/usr/bin/env python3
"""Perbarui isi artikel yang sudah tayang dari skrip generatornya.
Pakai: python3 ss_perbarui_artikel.py <skrip.py> <post_id> [--go]
"""
import base64, importlib.util, json, os, 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"}
BACKUP = f"{WS}/ss_fase1_backup"
os.makedirs(BACKUP, exist_ok=True)

skrip, pid = sys.argv[1], int(sys.argv[2])


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=180) 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"


spec = importlib.util.spec_from_file_location("gen", f"{WS}/{skrip}" if not skrip.startswith("/") else skrip)
m = importlib.util.module_from_spec(spec)
argv_simpan, sys.argv = sys.argv, [skrip]      # skrip generator jangan ikut menulis
try:
    spec.loader.exec_module(m)
except SystemExit:
    pass
sys.argv = argv_simpan
baru = m.ISI

st, lama = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,link,content")
if not isinstance(lama, dict):
    print("❌ baca gagal:", st, str(lama)[:120]); sys.exit(1)
raw_lama = lama["content"]["raw"]
open(f"{BACKUP}/post_{pid}_sebelum_perbaikan.txt", "w").write(raw_lama)

em_lama = raw_lama.count("—")
em_baru = baru.count("—")
print(f"   #{pid} {lama['slug']}")
print(f"   em dash: {em_lama} → {em_baru} | kata: {len(re.sub(r'<[^>]+>', ' ', raw_lama).split())} "
      f"→ {len(re.sub(r'<[^>]+>', ' ', baru).split())}")
if "--go" not in sys.argv:
    print("(dry run — pakai --go)")
    sys.exit(0)

st2, d2 = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"content": baru})
time.sleep(2)
st3, cek = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
raw2 = cek["content"]["raw"] if isinstance(cek, dict) else ""
r = urllib.request.Request(f"{S}/{lama['slug']}/?nocache={int(time.time())}", headers=UA)
with urllib.request.urlopen(r, timeout=120) as x:
    t = x.read().decode("utf-8", "replace")
print(f"   HTTP {st2} | em dash tersimpan: {raw2.count('—')} | em dash di halaman live: {t.count('—')}")
print(f"   {'✅' if raw2.count('—') == em_baru else '❌'} isi cocok")
