#!/usr/bin/env python3
"""Uji kenapa penulisan konten TSC mengembalikan 404 — TANPA mengubah isi (menulis ulang isi yang sama)."""
import base64, importlib.util, json, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def call(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(f"https://{DOM}{path}", data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            return x.status, x.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()[:400]
    except Exception as e:
        return "GAGAL", str(e)[:120].encode()


PID = 1644
st, body = call(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=id,content")
print("1. baca:", st)
d = json.loads(body)
raw = d["content"]["raw"]
print(f"   panjang isi: {len(raw)} char")

# tulis ulang isi yang SAMA (tidak mengubah apa pun)
st2, body2 = call(f"/wp-json/wp/v2/posts/{PID}", "POST", {"content": raw})
print("2. tulis ulang isi sama:", st2, body2[:180].decode("utf-8", "replace"))

# tulis ulang dengan perubahan sepele yang aman (spasi di akhir) untuk melihat perilakunya
st3, body3 = call(f"/wp-json/wp/v2/posts/{PID}", "POST", {"content": raw + "\n"})
print("3. tulis ulang + baris kosong:", st3, body3[:180].decode("utf-8", "replace"))

# kembalikan ke bentuk semula
st4, _ = call(f"/wp-json/wp/v2/posts/{PID}", "POST", {"content": raw})
print("4. dikembalikan:", st4)
