#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Verifikasi baca-balik 5 artikel gap: HTTP 200, status, meta Yoast, schema FAQ, tombol WA."""
import base64, json, re, subprocess, urllib.request, urllib.error

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}


def api(path):
    r = urllib.request.Request(S + path, headers=H)
    with urllib.request.urlopen(r, timeout=120) as x:
        return json.loads(x.read())


def http(url):
    r = subprocess.run(["curl", "-4", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                        "-L", "--max-time", "40", f"{url}?cb=1"], capture_output=True, text=True)
    return r.stdout.strip()


hasil = json.load(open("ss_artikel_gap_hasil.json"))
for h in hasil:
    d = api(f"/wp-json/wp/v2/posts/{h['id']}?context=edit&_fields=slug,status,link,meta,content,categories,tags,excerpt")
    m = d.get("meta") or {}
    isi = (d.get("content") or {}).get("raw", "")
    kode = http(h["link"])
    print(f"\n#{h['id']} http={kode} status={d['status']} slug={d['slug']}")
    print(f"   focuskw  : {m.get('_yoast_wpseo_focuskw')}")
    print(f"   title    : {m.get('_yoast_wpseo_title')}")
    print(f"   metadesc : {str(m.get('_yoast_wpseo_metadesc'))[:90]}... ({len(str(m.get('_yoast_wpseo_metadesc')))} char)")
    print(f"   excerpt  : {'ADA' if (d.get('excerpt') or {}).get('raw') else 'KOSONG'}")
    print(f"   kategori : {d.get('categories')} tags: {d.get('tags')}")
    print(f"   FAQ schema: {'ADA' if 'FAQPage' in isi else 'TIDAK ADA'} | tombol WA: {'ADA' if 'wa.me/6281935000624' in isi else 'TIDAK ADA'}")
    print(f"   internal link: {len(re.findall(r'https://studiosoft.id/', isi))} | outbound: {len(re.findall(r'href=.https?://(?!studiosoft)', isi))}")
