#!/usr/bin/env python3
"""Cek kondisi StudioSoft setelah restart: kecepatan, antrean tayang, dan progres pekerjaan."""
import base64, html, json, re, time, urllib.request

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


def api(path, ulang=2):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    r = urllib.request.Request(S + path, headers=h)
    for _ in range(ulang):
        t0 = time.time()
        try:
            with urllib.request.urlopen(r, timeout=90) as x:
                return json.loads(x.read()), time.time() - t0
        except Exception as e:
            err = e
    return {"error": str(err)[:80]}, time.time() - t0


print("=== 1. Kecepatan API & halaman ===")
d, dt = api("/wp-json/wp/v2/posts?per_page=1&_fields=id")
print(f"  REST API   : {'OK' if 'error' not in d else d['error']} | {dt:.2f}s")
try:
    t0 = time.time()
    r = urllib.request.Request(S + "/", headers={"User-Agent": "Mozilla/5.0"})
    resp = urllib.request.urlopen(r, timeout=60)
    resp.read()
    print(f"  homepage   : {resp.status} | {time.time()-t0:.2f}s | cf-cache {resp.headers.get('cf-cache-status','-')}")
except Exception as e:
    print("  homepage   :", str(e)[:70])

print("\n=== 2. Antrean tayang 08:00 WIB ===")
d, _ = api("/wp-json/wp/v2/posts?per_page=20&status=future&orderby=date&order=asc&_fields=id,title,date,status")
if isinstance(d, list):
    print(f"  artikel terjadwal: {len(d)}")
    for p in d:
        print(f"    #{p['id']} {p['date']} | {html.unescape(p['title']['rendered'])[:56]}")
else:
    print("  ", str(d)[:100])

print("\n=== 3. Progres pekerjaan (307 artikel) ===")
posts, page = [], 1
while True:
    d, _ = api(f"/wp-json/wp/v2/posts?per_page=100&page={page}&context=edit&_fields=id,content,meta,featured_media")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1
kata_kurang = faq_kurang = link_kurang = 0
for p in posts:
    raw = p["content"]["raw"] if isinstance(p["content"], dict) else ""
    if len(html.unescape(re.sub(r"<[^>]+>", " ", raw)).split()) < 1000:
        kata_kurang += 1
    if "FAQPage" not in raw:
        faq_kurang += 1
    if not re.search(r'href="https://studiosoft\.id/', raw):
        link_kurang += 1
print(f"  total artikel publish     : {len(posts)}")
print(f"  masih < 1.000 kata        : {kata_kurang}")
print(f"  masih tanpa FAQ + schema  : {faq_kurang}")
print(f"  masih tanpa link internal : {link_kurang}")
