#!/usr/bin/env python3
"""Data untuk lima kata kunci yang diminta Bos: kondisi GSC, halaman yang ada, dan pesaing di Google & peta."""
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"

T = json.load(open(f"{WS}/.serper_token.json"))
KEY = T.get("api_key") or T.get("key") or list(T.values())[0]
SH = {"User-Agent": "Mozilla/5.0", "X-API-KEY": KEY, "Content-Type": "application/json"}

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": ["query"],
    "rowLimit": 3000}).execute().get("rows", [])

TOPIK = {"kecantikan": r"kecantikan", "estetika": r"estetik", "tato": r"tato|tahi lalat",
         "jerawat": r"jerawat", "facial": r"facial"}
print(f"=== GSC 90 hari: kueri per topik (dari {len(rows)} kueri) ===")
for nama, pola in TOPIK.items():
    cocok = [(r["keys"][0], int(r["impressions"]), int(r["clicks"]), round(r["position"], 1))
             for r in rows if re.search(pola, r["keys"][0], re.I)]
    cocok.sort(key=lambda x: -x[1])
    tot = sum(x[1] for x in cocok)
    print(f"\n  [{nama}] {len(cocok)} kueri · {tot} tayangan")
    for k, t, c, p in cocok[:8]:
        print(f"     {t:>4} tayang · {c} klik · pos {p:>5} · «{k[:58]}»")

print("\n=== halaman/artikel TSC yang bersinggungan ===")
for jenis in ("posts", "pages"):
    u = f"{SITUS}/wp-json/wp/v2/{jenis}?per_page=100&status=publish&_fields=id,slug,title"
    for x in json.loads(urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=120).read()):
        teks = (x["slug"] + " " + re.sub("<[^>]+>", "", x["title"]["rendered"])).lower()
        if re.search(r"kecantikan|estetik|tato|tahi-lalat|tahi lalat|jerawat|facial", teks):
            print(f"   {jenis:<5} #{x['id']:<6} {x['slug'][:64]}")

KATA = ["klinik kecantikan krian", "klinik estetika krian", "klinik hapus tato sidoarjo",
        "solusi jerawat", "klinik facial krian", "klinik kecantikan estetika krian sidoarjo"]


def serper(path, body):
    r = urllib.request.Request(f"https://google.serper.dev/{path}",
                               data=json.dumps(body).encode(), headers=SH)
    try:
        return json.loads(urllib.request.urlopen(r, timeout=60).read())
    except Exception as e:
        return {"err": str(e)[:40]}


print("\n=== pesaing organik & peta ===")
for kw in KATA:
    d = serper("search", {"q": kw, "gl": "id", "hl": "id", "num": 20})
    org = d.get("organic", [])
    pos = next((i for i, h in enumerate(org, 1) if "theskincodeclinic" in str(h.get("link", "")).lower()), None)
    print(f"\n  «{kw}» → TSC {'#' + str(pos) if pos else 'di luar 20'}")
    for h in org[:3]:
        print(f"      {str(h.get('link', ''))[:70]}")
    time.sleep(0.3)
    pl = serper("places", {"q": kw, "gl": "id", "hl": "id"}).get("places", [])
    if pl:
        print("      peta:", " · ".join(f"{str(p.get('title'))[:26]} ({p.get('ratingCount')} ulasan)"
                                       for p in pl[:3]))
