#!/usr/bin/env python3
"""Cari halaman 'tayangan besar, klik nol' di setiap klien aktif: peluang CTR tercepat."""
import importlib.util, json, os
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("kpi", f"{WS}/kpi_konfigurasi_klien.py")
kpi = importlib.util.module_from_spec(spec)
spec.loader.exec_module(kpi)

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)

ringkas = {}
for k in kpi.KLIEN:
    nama, site = k["nama"], k["gsc"]
    try:
        rows = gsc.searchanalytics().query(siteUrl=site, body={
            "startDate": AWAL.isoformat(), "endDate": AKHIR.isoformat(), "dimensions": ["page"],
            "rowLimit": 2000}).execute().get("rows", [])
    except Exception as e:
        print(f"\n■ {nama}: gagal ({str(e)[:60]})")
        continue
    hal = [{"url": r["keys"][0], "tayang": int(r["impressions"]), "klik": int(r["clicks"]),
            "posisi": round(r["position"], 1)} for r in rows]
    nolk = sorted([h for h in hal if h["klik"] == 0 and h["tayang"] >= 100],
                  key=lambda x: -x["tayang"])
    tipis = sorted([h for h in hal if 0 < h["klik"] and h["tayang"] >= 200
                    and h["klik"] / h["tayang"] < 0.01], key=lambda x: -x["tayang"])
    ringkas[nama] = {"total_halaman": len(hal), "nol_klik": nolk[:8], "ctr_rendah": tipis[:5],
                     "jumlah_nol_klik": len(nolk), "jumlah_ctr_rendah": len(tipis)}
    print(f"\n■ {nama} · {len(hal)} halaman berdata · nol klik (>=100 tayangan): {len(nolk)} · "
          f"CTR <1% (>=200 tayangan): {len(tipis)}")
    for h in nolk[:5]:
        print(f"     {h['tayang']:>5} tayang · 0 klik · pos {h['posisi']:>5} | {h['url'].replace('https://','')[:74]}")

json.dump(ringkas, open(f"{WS}/drafts/seo_peluang_ctr.json", "w"), ensure_ascii=False, indent=1)
print(f"\n→ drafts/seo_peluang_ctr.json")
