#!/usr/bin/env python3
"""TSC: survei HALAMAN (page) — judul SEO, meta, panjang isi, tautan WA, plus data GSC & GA4 per halaman."""
import base64, html, json, os, re, time, urllib.request, importlib.util
from google.oauth2 import service_account
from googleapiclient.discovery import build

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
spec = importlib.util.spec_from_file_location("cfg_tsc", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM, AUTH = m.CFG["domain"], base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


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=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(3)
    return []


print("=== GSC: data per HALAMAN (90 hari) ===")
gsc = build("searchconsole", "v1", credentials=service_account.Credentials.from_service_account_file(
    KEY, scopes=["https://www.googleapis.com/auth/webmasters.readonly"]), cache_discovery=False)
rows = gsc.searchanalytics().query(siteUrl="https://www.theskincodeclinic.com/", body={
    "startDate": "2026-06-28", "endDate": "2026-09-25", "dimensions": ["page"], "rowLimit": 5000}).execute().get("rows", [])
peta = {}
for r in rows:
    u = r["keys"][0].replace("https://www.theskincodeclinic.com", "").rstrip("/") or "/"
    peta[u] = {"imp": r["impressions"], "klik": r["clicks"], "pos": round(r["position"], 1), "ctr": round(r["ctr"] * 100, 2)}

print("=== GA4: sesi per halaman (90 hari) ===")
ga = build("analyticsdata", "v1beta", credentials=service_account.Credentials.from_service_account_file(
    KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)
ga_map = {}
r = ga.properties().runReport(property="properties/490140645", body={
    "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
    "dimensions": [{"name": "landingPagePlusQueryString"}], "metrics": [{"name": "sessions"}],
    "limit": 300}).execute()
for row in r.get("rows", []):
    u = row["dimensionValues"][0]["value"].split("?")[0].rstrip("/") or "/"
    ga_map[u] = ga_map.get(u, 0) + int(row["metricValues"][0]["value"])

print("\n=== HALAMAN (page) di WordPress ===")
pages = rest("/wp-json/wp/v2/pages?per_page=100&context=edit&_fields=id,slug,link,title,content,author,status")
for p in pages:
    raw = p.get("content", {}).get("raw", "")
    teks = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<script.*?</script>", " ", raw, flags=re.S))))
    kata = len([w for w in teks.split() if w])
    u = "/" + p["slug"] if p["slug"] else "/"
    g = peta.get(u, {})
    wa = len(re.findall(r"(?:wa\.me|api\.whatsapp\.com)", raw))
    print(f"\n   #{p['id']} /{p['slug']}  [{p['status']}] penulis id {p['author']}")
    print(f"      judul WP : {html.unescape(p['title']['raw'])}")
    print(f"      {kata} kata | {len(raw)} char | tautan WA di isi: {wa}")
    print(f"      GSC: imp {g.get('imp', 0)} klik {g.get('klik', 0)} pos {g.get('pos', '-')} | GA4 sesi: {ga_map.get(u, 0)}")
    link_int = sorted(set(re.findall(r'href="https://www\.theskincodeclinic\.com(/[^"]*)"', raw)))
    print(f"      tautan internal di isi: {link_int[:5]}")
