#!/usr/bin/env python3
"""Cek halaman-halaman jasa pembuatan website StudioSoft: performa + judul/meta sekarang."""
import base64, html, json, os, re, urllib.request
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/webmasters.readonly"])
gsc = build("webmasters", "v3", credentials=creds, cache_discovery=False)
S = "https://studiosoft.id/"
e = date.today() - timedelta(days=2)
S90, END = (e - timedelta(days=89)).isoformat(), e.isoformat()
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()

URLS = ["/jasa-pembuatan-website/", "/jasa-pembuatan-website-wordpress-surabaya-terpercaya/",
        "/jasa-pembuatan-website-profesional-untuk-usaha-jasa-di-surabaya/",
        "/berapa-biaya-jasa-pembuatan-website/",
        "/8-paket-jasa-pembuatan-website-wordpress-surabaya-termurah-di-studiosoft/"]

print("=== performa 90 hari per halaman (query 'website') ===")
for u in URLS:
    b = {"startDate": S90, "endDate": END, "dimensions": ["query"],
         "dimensionFilterGroups": [{"filters": [
             {"dimension": "page", "operator": "equals", "expression": S.rstrip('/') + u},
             {"dimension": "query", "operator": "contains", "expression": "website"}]}],
         "rowLimit": 5}
    r = gsc.searchanalytics().query(siteUrl=S, body=b).execute().get("rows", [])
    tot = sum(int(x["impressions"]) for x in r)
    pos = (sum(x["position"] * x["impressions"] for x in r) / tot) if tot else 0
    print(f"\n  {u}\n     impresi 'website': {tot} | posisi rata2: {pos:.1f}")
    for x in r[:3]:
        print(f"       {int(x['impressions']):>3} imp | pos {x['position']:>5.1f} | {x['keys'][0]}")


def wp(path):
    req = urllib.request.Request("https://studiosoft.id" + path, headers={"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(req, timeout=120) as x:
            return json.loads(x.read())
    except Exception as ex:
        return {"error": str(ex)[:80]}


print("\n=== judul SEO & meta halaman kandidat (versi WordPress) ===")
for u in URLS:
    slug = u.strip("/")
    d = wp(f"/wp-json/wp/v2/posts?slug={slug}&context=edit&_fields=id,title,meta,link")
    if isinstance(d, dict) and d.get("error"):
        print(f"  {u} → error {d['error']}")
        continue
    if not d:
        print(f"  {u} → (bukan post / tidak ketemu)")
        continue
    p = d[0]
    m = p.get("meta", {})
    print(f"\n  #{p['id']} {u}")
    print(f"     fk   : {m.get('_yoast_wpseo_focuskw','')}")
    print(f"     title: {m.get('_yoast_wpseo_title','') or '(default)'}")
    print(f"     meta : {len(m.get('_yoast_wpseo_metadesc','') or '')} char | {(m.get('_yoast_wpseo_metadesc','') or '')[:90]}")
