#!/usr/bin/env python3
"""Verifikasi akhir #3761: skema FAQPage valid, 5 pertanyaan cocok isi, media 200, judul/meta tak berubah."""
import base64, json, re, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
PID = 3761


def rest(path):
    r = urllib.request.Request(f"https://{DOM}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    with urllib.request.urlopen(r, timeout=120) as x:
        return json.loads(x.read())


c = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=id,slug,status,title,content,excerpt,meta,"
         f"categories,tags,featured_media,modified")
raw = c["content"]["raw"]
teks = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", raw, flags=re.S | re.I)))

print(f"  status      : {c['status']}  (harus draft)")
print(f"  judul       : {c['title']['raw']}")
print(f"  slug        : {c['slug']}")
print(f"  diubah      : {c['modified']}")

m = re.search(r'<script type="application/ld\+json">(.*?)</script>', raw, re.S)
sk = json.loads(m.group(1))
print(f"\n  skema tipe  : {sk['@type']}  | @context: {sk['@context']}")
print(f"  jumlah FAQ  : {len(sk['mainEntity'])}")
ok = True
for i, q in enumerate(sk["mainEntity"], 1):
    tanya = q["name"]
    jawab = q["acceptedAnswer"]["text"]
    ada_t = tanya in raw
    # jawaban ada di isi (setelah normalisasi spasi dan tanpa tag)
    ada_j = re.sub(r"\s+", " ", jawab).strip() in teks
    print(f"   {i}. {'OK ' if (ada_t and ada_j) else 'GAGAL'} pertanyaan={ada_t} jawaban={ada_j} | {tanya[:60]}")
    ok = ok and ada_t and ada_j
print(f"  skema selaras isi: {'YA' if ok else 'TIDAK'}")

med = rest(f"/wp-json/wp/v2/media/{c['featured_media']}?context=edit&_fields=id,source_url,alt_text,"
           f"media_details,title")
print(f"\n  foto utama  : #{med['id']} {med['source_url']}")
print(f"  alt         : {med['alt_text'][:90]}...")
print(f"  dimensi     : {med['media_details'].get('width')}x{med['media_details'].get('height')} "
      f"({med['media_details'].get('filesize', 0)//1024} byte)")
try:
    with urllib.request.urlopen(urllib.request.Request(med["source_url"], headers=UA), timeout=60) as x:
        print(f"  foto publik : HTTP {x.status} | {x.headers.get('Content-Type')} | {len(x.read())//1024} KB")
except urllib.error.HTTPError as e:
    print(f"  foto publik : HTTP {e.code}")

print(f"\n  meta Yoast  : {json.dumps({k: v for k, v in (c['meta'] or {}).items() if 'yoast' in k}, ensure_ascii=False)}")
print(f"  kategori    : {c['categories']} | tag: {c['tags']}")
print(f"  kutip ganda (excerpt): {c['excerpt']['raw'][:120]!r}")
print(f"\n  kata        : {len([w for w in re.split(chr(32), teks) if w])}")
print(f"  tombol WA   : {'ada' if 'wa.me/6281909222026' in raw else 'TIDAK'}")
