#!/usr/bin/env python3
"""Konsolidasi DAS gelombang 2: duplikat yang lebih jelas (Brio, matic, minggu, honda)."""
import base64, html, json, os, re, sys, urllib.request, urllib.error

SITE = "https://dasindonesia.com"
AUTH = base64.b64encode(b"bambangbot:u3a1 G2pQ 3SWY f0zI OlGP YAjU").decode()
WS = os.path.dirname(os.path.abspath(__file__))
MERGE = {
    6726: 6722,   # servis Honda Brio -> Bengkel Mobil Honda Brio Terbaik
    6571: 6722,   # bengkel spesialis Brio -> idem
    6931: 6722,   # 6 alasan Brio dirawat di DAS -> idem
    7626: 7777,   # tips merawat transmisi matic -> cara merawat transmisi matic
    6730: 6661,   # cari bengkel Honda terpercaya -> Bengkel Honda Terbaik
    8298: None,   # Bengkel Buka Hari Minggu -> akan diarahkan ke halaman minggu yang sudah ada
}
RETIRE = [6411, 6916, 5449, 6867]


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"
    r = urllib.request.Request(SITE + path, data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=240) as x:
            return x.status, json.loads(x.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:200]


def ambil(pid):
    st, p = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,title,content,status")
    return p if isinstance(p, dict) else None


def seksi(raw):
    idx = [m.start() for m in re.finditer(r"<h2[^>]*>", raw, re.I)]
    if not idx:
        return []
    idx.append(len(raw))
    out = []
    for i in range(len(idx) - 1):
        blok = raw[idx[i]:idx[i + 1]]
        jud = re.search(r"<h2[^>]*>(.*?)</h2>", blok, re.S | re.I)
        out.append((html.unescape(re.sub("<[^>]+>", "", jud.group(1))).strip() if jud else "", blok.strip()))
    return out


# cari halaman "buka hari minggu" yang sudah punya impresi
st, d = api("/wp-json/wp/v2/posts?slug=hari-minggu-tetap-buka&context=edit&_fields=id,title,content,status")
if isinstance(d, list) and d:
    MERGE[8298] = d[0]["id"]
    print(f"halaman minggu utama: #{d[0]['id']} {d[0]['title']['rendered'][:50]}")
else:
    MERGE.pop(8298, None)

apply_ = "--apply" in sys.argv
for src, dst in sorted(MERGE.items()):
    s, t = ambil(src), ambil(dst)
    if not s or not t:
        print(f"  #{src} -> #{dst}: GAGAL ambil"); continue
    judul_t = {h.lower() for h, _ in seksi(t["content"]["raw"])}
    pilih = [(h, b) for h, b in seksi(s["content"]["raw"])
             if h and h.lower() not in judul_t and not re.search(r"faq|kesimpulan|baca juga", h, re.I)][:2]
    print(f"  #{src} {s['title']['rendered'][:42]:<44} -> #{dst} | bagian unik: {len(pilih)}")
    for h, _ in pilih:
        print(f"        + {h[:68]}")
    if apply_:
        if pilih:
            blok = "\n".join(b for _, b in pilih)
            raw_t = t["content"]["raw"]
            m = re.search(r"\n<h2[^>]*>\s*(FAQ|Kesimpulan)", raw_t, re.I)
            baru = (raw_t[:m.start()] + "\n" + blok + "\n" + raw_t[m.start():]) if m else (raw_t.rstrip() + "\n" + blok + "\n")
            stx, _ = api(f"/wp-json/wp/v2/posts/{dst}", {"content": baru})
            _, chk = api(f"/wp-json/wp/v2/posts/{dst}?context=edit&_fields=content")
            print(f"        gabung: {'OK' if isinstance(chk, dict) and len(chk['content']['raw']) > len(raw_t) else 'GAGAL'}")
        sty, _ = api(f"/wp-json/wp/v2/posts/{src}", {"status": "draft"})
        print(f"        pensiun #{src}: {'draft' if sty == 200 else sty}")

print("\n=== pensiun langsung ===")
for pid in RETIRE:
    p = ambil(pid)
    if not p:
        print(f"  #{pid} tidak ditemukan"); continue
    print(f"  #{pid} {p['title']['rendered'][:60]} [{p['status']}]")
    if apply_:
        st, _ = api(f"/wp-json/wp/v2/posts/{pid}", {"status": "draft"})
        print(f"        pensiun: {'draft' if st == 200 else st}")
if not apply_:
    print("\n(dry run)")
