#!/usr/bin/env python3
"""Cari penyebutan 'tato' di seluruh isi TSC, dan ukur performa tiap halaman klaster kecantikan/estetika/jerawat/facial."""
import base64, importlib.util, json, os, re, time, urllib.request
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
A = base64.b64encode(f"{m.CFG['user']}:{m.CFG['pass']}".encode()).decode()
H = {"Authorization": f"Basic {A}", "User-Agent": "Mozilla/5.0"}
SITUS = "https://www.theskincodeclinic.com"

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)
AKHIR = date.today() - timedelta(days=2)
AWAL = AKHIR - timedelta(days=89)
rows = gsc.searchanalytics().query(siteUrl=SITUS + "/", body={
    "startDate": AWAL.isoformat(), "endDate": AKHIR.isoformat(), "dimensions": ["page"],
    "rowLimit": 2000}).execute().get("rows", [])
perf = {r["keys"][0]: (int(r["impressions"]), int(r["clicks"]), round(r["position"], 1)) for r in rows}

print("=== penyebutan 'tato' di isi situs ===")
ada_tato = []
for jenis in ("posts", "pages"):
    for hal in range(1, 6):
        u = (f"{SITUS}/wp-json/wp/v2/{jenis}?per_page=100&page={hal}&status=publish"
             f"&context=edit&_fields=id,slug,title,content,link")
        try:
            d = json.loads(urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=120).read())
        except Exception:
            break
        if not d:
            break
        for x in d:
            c = x["content"]["raw"] if isinstance(x.get("content"), dict) else ""
            if re.search(r"\btato\b|tattoo|tato permanen|hapus tato", c, re.I):
                ada_tato.append((jenis, x["id"], x["slug"]))
        if len(d) < 100:
            break
print(f"   {len(ada_tato)} halaman menyebut tato")
for j, i, s in ada_tato[:12]:
    print(f"     {j:<5} #{i:<6} {s[:66]}")

print("\n=== performa halaman klaster (GSC 90 hari) ===")
klaster = []
for jenis in ("posts", "pages"):
    for hal in range(1, 6):
        u = f"{SITUS}/wp-json/wp/v2/{jenis}?per_page=100&page={hal}&status=publish&_fields=id,slug,link"
        try:
            d = json.loads(urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=120).read())
        except Exception:
            break
        if not d:
            break
        for x in d:
            s = x["slug"].lower()
            if re.search(r"kecantikan|estetik|jerawat|facial|wajah|tato|tahi-lalat", s):
                t, k, p = perf.get(x["link"], (0, 0, 0))
                klaster.append((t, k, p, jenis, x["id"], s))
        if len(d) < 100:
            break
klaster.sort(key=lambda z: -z[0])
print(f"   {len(klaster)} halaman")
for t, k, p, j, i, s in klaster[:28]:
    tanda = "  ← jalan" if t >= 20 else ""
    print(f"     {t:>5} tayang · {k:>2} klik · pos {p:>5} · {j:<5} #{i:<6} {s[:56]}{tanda}")
