#!/usr/bin/env python3
"""Audit artikel LEIT penyasar query uang (versi cepat: 1x fetch semua konten)."""
import base64, html, json, os, re, urllib.request
from google.auth.transport.requests import Request
from google.oauth2 import service_account

SITE = "https://www.leitsurabaya.com"
AUTH = base64.b64encode(b"bambangbot:zibd dLIV xY8x onP9 39qL hiNr").decode()

TARGET = {
    3928: "kursus bahasa inggris surabaya timur",
    3925: "les bahasa inggris surabaya barat",
    3825: "kursus bahasa inggris paling terjangkau surabaya",
    3827: "rekomendasi kursus bahasa inggris terjangkau surabaya",
    3902: "les bahasa inggris terdekat surabaya",
    3903: "tempat les bahasa inggris terdekat surabaya",
    3904: "les bahasa inggris terdekat dari rumah",
}


def api(path):
    r = urllib.request.Request(SITE + path, headers={"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(r, timeout=240) as x:
        return json.loads(x.read())


posts = api("/wp-json/wp/v2/posts?per_page=100&context=edit&_fields=id,link,slug,title,content")
linkmap = {p["id"]: p["link"] for p in posts}
inlinks = {i: [] for i in TARGET}
for p in posts:
    raw = p["content"]["raw"]
    for t in TARGET:
        if t != p["id"] and linkmap[t] in raw:
            inlinks[t].append(p["id"])

print("=== AUDIT ARTIKEL QUERY UANG ===")
for p in posts:
    pid = p["id"]
    if pid not in TARGET:
        continue
    raw = p["content"]["raw"]
    text = html.unescape(re.sub(r"<[^>]+>", " ", raw))
    words = len(text.split())
    h1 = [re.sub("<[^>]+>", "", x) for x in re.findall(r"<h1[^>]*>(.*?)</h1>", raw, re.S)]
    h2 = [re.sub("<[^>]+>", "", x) for x in re.findall(r"<h2[^>]*>(.*?)</h2>", raw, re.S)]
    out_links = len(set(re.findall(r'href="https://www\.leitsurabaya\.com/([^"#?]+)', raw)))
    print(f"\n#{pid} {p['link']}")
    print(f"   judul WP  : {html.unescape(p['title']['rendered'])[:110]}")
    print(f"   H1        : {[x[:70] for x in h1] or 'TIDAK ADA H1'}")
    print(f"   {words} kata | FAQPage: {'ADA' if 'FAQPage' in raw else 'TIDAK'} | heading FAQ: {'ada' if any('faq' in h.lower() for h in h2) else 'tidak'}")
    print(f"   link keluar: {out_links} | penaut masuk: {len(inlinks[pid])} → {sorted(inlinks[pid])}")
    print(f"   keyphrase target: {TARGET[pid]}")
    print(f"   H2: {' // '.join(x[:38] for x in h2[:6])}")

print("\n=== URL INSPECTION (status index) ===")
creds = service_account.Credentials.from_service_account_file(os.path.expanduser("~/.hermes/gsc_service_account.json"),
                                                              scopes=["https://www.googleapis.com/auth/webmasters.readonly"])
creds.refresh(Request())
for pid in sorted(TARGET):
    body = json.dumps({"inspectionUrl": linkmap[pid], "siteUrl": "https://www.leitsurabaya.com/"}).encode()
    req = urllib.request.Request("https://searchconsole.googleapis.com/v1/urlInspection/index:inspect", data=body,
                                 headers={"Authorization": f"Bearer {creds.token}", "Content-Type": "application/json"})
    try:
        res = json.load(urllib.request.urlopen(req, timeout=60))
        st = res.get("inspectionResult", {}).get("indexStatusResult", {})
        print(f"  #{pid} {st.get('coverageState')} | crawl terakhir: {str(st.get('lastCrawlTime'))[:10]}")
    except Exception as e:
        print(f"  #{pid} ERROR {str(e)[:120]}")
