#!/usr/bin/env python3
"""Optimasi #3770: rapikan FAQ dobel, tambah paket & harga (angka asli dari #3496) + tautan portofolio,
bangun ulang schema FAQPage. Dry run default."""
import base64, html, json, re, sys, urllib.request, urllib.error

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
PID = 3770
PAKET_URL = "https://studiosoft.id/8-paket-jasa-pembuatan-website-wordpress-surabaya-termurah-di-studiosoft/"
PORTFOLIO_URL = "https://studiosoft.id/portfolio/"


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


st, p = api(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=content,meta,link")
raw = p["content"]["raw"]
asli = raw

# 1. hapus blok FAQ pertama (versi lama, dobel)
m = re.search(r'\n?<h2[^>]*>\s*FAQ\s*[–-]\s*Pertanyaan yang Sering Diajukan\s*</h2>.*?(?=<hr class="wp-block-separator|<h2[^>]*>\s*(?:Baca Juga|FAQ\s*</h2>))', raw, re.S | re.I)
if m:
    print(f"blok FAQ lama ditemukan: {m.end()-m.start()} char → akan dihapus")
    raw = raw[:m.start()] + "\n" + raw[m.end():]
else:
    print("blok FAQ lama TIDAK ditemukan")

# 2. tambah bagian paket & harga sebelum FAQ
BAGIAN = (
    "\n<h2>Paket dan Kisaran Harga</h2>\n"
    "<p>Di StudioSoft, jasa pembuatan website Surabaya mulai <strong>Rp 3,5 juta</strong> untuk website profil UMKM, "
    "sampai <strong>Rp 20 juta</strong> untuk kebutuhan yang lebih kompleks seperti katalog, booking, atau integrasi sistem. "
    "Harga sudah termasuk domain dan hosting satu tahun.</p>\n"
    f'<p>Rincian kedelapan paketnya, lengkap dengan fitur dan peruntukan bisnisnya, ada di '
    f'<a href="{PAKET_URL}">paket jasa pembuatan website WordPress Surabaya</a>. '
    f'Hasil pekerjaan yang sudah tayang bisa dilihat di <a href="{PORTFOLIO_URL}">portofolio StudioSoft</a>.</p>\n'
)
if "Paket dan Kisaran Harga" not in raw:
    anchor = re.search(r'\n<h2[^>]*>\s*FAQ\s*</h2>', raw, re.I)
    if anchor:
        raw = raw[:anchor.start()] + BAGIAN + raw[anchor.start():]
        print("bagian paket & harga ditambahkan sebelum FAQ")
    else:
        raw = raw.replace('<h2>Baca Juga</h2>', BAGIAN + '\n<h2>Baca Juga</h2>')
        print("bagian paket & harga ditambahkan sebelum Baca Juga")
else:
    print("bagian paket & harga sudah ada")

# 3. bangun ulang schema FAQPage dari FAQ yang tersisa
pasangan = []
for mm in re.finditer(r"<h3[^>]*>(.*?)</h3>\s*<p>(.*?)</p>", raw, re.S | re.I):
    q = html.unescape(re.sub("<[^>]+>", " ", mm.group(1))).strip()
    a = html.unescape(re.sub("<[^>]+>", " ", mm.group(2))).strip()
    a = re.sub(r"\s+", " ", a)
    if q and a:
        pasangan.append((q, a))
print(f"pasangan FAQ yang akan dimasukkan schema: {len(pasangan)}")
for q, _ in pasangan:
    print("   •", q[:70])

raw = re.sub(r'<script type="application/ld\+json">\{"@context":"https://schema\.org","@type":"FAQPage".*?</script>', "", raw, flags=re.S)
if pasangan:
    schema = {"@context": "https://schema.org", "@type": "FAQPage",
              "mainEntity": [{"@type": "Question", "name": q, "acceptedAnswer": {"@type": "Answer", "text": a}} for q, a in pasangan]}
    raw = raw.rstrip() + "\n" + '<script type="application/ld+json">' + json.dumps(schema, ensure_ascii=False) + "</script>"

print(f"\npanjang konten: {len(asli)} → {len(raw)} char")

if "--apply" not in sys.argv:
    print("(dry run — pakai --apply untuk simpan)")
    sys.exit(0)

st, res = api(f"/wp-json/wp/v2/posts/{PID}", {"content": raw})
_, chk = api(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=content")
isi = chk["content"]["raw"]
print(f"POST {st} | FAQ dobel terhapus: {'ya' if 'Pertanyaan yang Sering Diajukan' not in isi else 'TIDAK'}")
print(f"  bagian harga: {'ada' if 'Paket dan Kisaran Harga' in isi else 'TIDAK'} | schema FAQPage: {isi.count('FAQPage')}")
