#!/usr/bin/env python3
"""EveryBe: periksa dua halaman nol klik — kueri yang masuk, judul/deskripsi saat ini, dan isinya."""
import base64, html, json, re, time, urllib.parse, urllib.request, urllib.error, importlib.util
from datetime import date, timedelta

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_everybe", f"{WS}/cfg_everybe.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG.get("domain", "www.everybeofficial.com")
AUTH = base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}
HALAMAN = ["/shop/", "/tone-up-body-lotion/"]

print("=== 1. kueri yang mendarat di halaman tersebut (90 hari) ===")
TOKEN = f"{WS}/seo-oauth/google_token_atun.json"
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
c = Credentials.from_authorized_user_file(TOKEN)
if c.expired and c.refresh_token:
    c.refresh(Request()); open(TOKEN, "w").write(c.to_json())
H = {"Authorization": f"Bearer {c.token}", "Content-Type": "application/json"}

SITE = None
d = json.loads(urllib.request.urlopen(urllib.request.Request("https://www.googleapis.com/webmasters/v3/sites", headers=H), timeout=90).read())
for s in d.get("siteEntry", []):
    if "everybe" in s["siteUrl"] and s.get("permissionLevel") == "siteOwner":
        SITE = s["siteUrl"]
        break
print("   properti:", SITE)
ENC = urllib.parse.quote(SITE, safe="")
akhir = date.today() - timedelta(days=3)
awal = akhir - timedelta(days=89)
isi = {"startDate": awal.isoformat(), "endDate": akhir.isoformat(),
       "dimensions": ["query", "page"], "rowLimit": 500}
rows = json.loads(urllib.request.urlopen(urllib.request.Request(
    f"https://www.googleapis.com/webmasters/v3/sites/{ENC}/searchAnalytics/query",
    data=json.dumps(isi).encode(), headers=H), timeout=120).read()).get("rows", [])
for h in HALAMAN:
    print(f"\n   {h}")
    temuan = [r for r in rows if r["keys"][1].endswith(h) or h.rstrip("/") in r["keys"][1]]
    if not temuan:
        print("      (tidak ada kueri terekam)")
    for r in sorted(temuan, key=lambda x: -x["impressions"])[:8]:
        print(f"      {r['clicks']:>2} klik | {r['impressions']:>3} tayang | pos {round(r['position'],1):>5} | {r['keys'][0][:52]}")

print("\n=== 2. kondisi live halaman ===")
for h in HALAMAN:
    try:
        r = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}{h}", headers=UA), timeout=90)
        html_teks = r.read().decode("utf-8", "replace")
        t = re.search(r"<title[^>]*>(.*?)</title>", html_teks, re.S)
        de = re.search(r'<meta name="description" content="([^"]*)"', html_teks, re.I)
        h1 = re.findall(r"<h1[^>]*>(.*?)</h1>", html_teks, re.S)
        bersih = lambda x: html.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", x))).strip()
        print(f"\n   {h} → status {r.status} | {len(html_teks):,} byte")
        print(f"      judul : {bersih(t.group(1))[:110] if t else '-'}")
        print(f"      desc  : {bersih(de.group(1))[:130] if de else '(TIDAK ADA)'}")
        print(f"      H1    : {[bersih(x)[:70] for x in h1[:2]]}")
        kopi = bersih(re.sub(r"<script.*?</script>|<style.*?</style>", " ", html_teks, flags=re.S))[:400]
        print(f"      isi   : {kopi[:260]}")
    except Exception as e:
        print(f"   {h} → gagal {str(e)[:70]}")

print("\n=== 3. halaman di WordPress (id + meta Yoast) ===")
def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(3)
    return []

slugs = [h.strip("/") for h in HALAMAN]
for slug in slugs:
    for jenis in ("pages", "posts"):
        d2 = rest(f"/wp-json/wp/v2/{jenis}?slug={slug}&context=edit&_fields=id,slug,title,meta,content")
        if isinstance(d2, list) and d2:
            p = d2[0]
            meta = p.get("meta") or {}
            yoast = {k: v for k, v in meta.items() if "yoast" in k}
            print(f"   {jenis[:-1]} #{p['id']} /{p['slug']} | panjang isi {len(p['content']['raw']):,}")
            print(f"      judul WP : {html.unescape(re.sub('<[^>]+>','',p['title']['raw']))[:80]}")
            print(f"      meta     : {json.dumps(yoast)[:200] if yoast else '(tidak ada kunci Yoast di REST)'}")
            break
