#!/usr/bin/env python3
"""Perbaiki tag (masih sisa 'Instagram, Threads') + tambah link internal di 5 artikel batch 1."""
import base64, json, re, time, urllib.request, urllib.error

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()

TAG_BARU = {
    7528: ["AI", "Digital Marketing", "Karier Digital"],
    7529: ["AI", "GEO", "SEO"],
    7530: ["AI", "Prompt AI", "Produktivitas"],
    7531: ["AI", "Content Marketing", "SEO"],
    7532: ["AI", "Tools AI", "Digital Marketing"],
}
LINK_TAMBAHAN = {
    7529: ('<h2>Baca juga</h2>\n<p>Kalau Anda ingin melihat penerapannya di bisnis nyata, baca '
           '<a href="https://studiosoft.id/konsultan-ai-surabaya/">layanan konsultan AI Surabaya</a> '
           'dan <a href="https://studiosoft.id/masa-depan-seo-antara-manusia-ai-dan-google-di-2026/">masa depan SEO di era AI</a>.</p>',
           '<h2>Kesimpulan</h2>'),
    7530: ('<h2>Baca juga</h2>\n<p>Untuk melihat bagaimana prompt dipakai di produksi konten harian, lihat '
           '<a href="https://studiosoft.id/ai-untuk-konten-marketing-menulis-artikel-seo-yang-disukai-google/">AI untuk konten marketing</a> '
           'dan <a href="https://studiosoft.id/otomasi-bisnis-dengan-ai/">otomasi bisnis dengan AI</a>.</p>',
           '<h2>Kesimpulan</h2>'),
    7531: ('<h2>Baca juga</h2>\n<p>Panduan praktis menerapkannya ada di '
           '<a href="https://studiosoft.id/implementasi-ai-untuk-umkm/">implementasi AI untuk UMKM</a> '
           'dan <a href="https://studiosoft.id/ai-untuk-konten-marketing-menulis-artikel-seo-yang-disukai-google/">AI untuk konten marketing</a>.</p>',
           '<h2>Kesimpulan</h2>'),
}


def api(path, data=None):
    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(S + path, data=body, headers=h, method="POST" if data else "GET")
    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, 500, 502, 503, 504):
                time.sleep(3); continue
            return e.code, e.read().decode()[:200]
        except Exception as e:
            time.sleep(3); err = e
    return 0, str(err)[:150]


def tag_id(nama):
    st, d = api(f"/wp-json/wp/v2/tags?slug={nama.lower().replace(' ', '-')}&_fields=id,name")
    if isinstance(d, list) and d:
        return d[0]["id"]
    st, baru = api("/wp-json/wp/v2/tags", {"name": nama})
    return baru.get("id") if isinstance(baru, dict) else None


print("=== 1. Ganti tag jadi relevan ===")
for pid, tags in TAG_BARU.items():
    ids = [i for i in (tag_id(t) for t in tags) if i]
    st, _ = api(f"/wp-json/wp/v2/posts/{pid}", {"tags": ids})
    st2, chk = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=tags")
    nm = api(f"/wp-json/wp/v2/tags?include={','.join(map(str, chk.get('tags',[])))}&_fields=name")
    print(f"  #{pid} POST {st} → tag sekarang: {', '.join(t['name'] for t in nm[1])}")

print("\n=== 2. Tambah link internal ===")
for pid, (blok, anchor) in LINK_TAMBAHAN.items():
    st, p = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    raw = p["content"]["raw"]
    if "Baca juga</h2>" in raw:
        print(f"  #{pid} sudah ada — skip"); continue
    baru = raw.replace(anchor, blok + "\n" + anchor, 1)
    st2, _ = api(f"/wp-json/wp/v2/posts/{pid}", {"content": baru})
    st3, chk = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    n = len(set(re.findall(r'href="https://studiosoft\.id/([^"#?]+)', chk["content"]["raw"])))
    print(f"  #{pid} POST {st2} | link internal sekarang: {n}")
