#!/usr/bin/env python3
"""Kenapa CTR StudioSoft kecil: bedah tayangan menurut posisi, dan halaman halaman-1 yang tetap nol klik."""
import os
from collections import defaultdict
from datetime import date, timedelta

from google.oauth2 import service_account
from googleapiclient.discovery import build

SITUS = "https://studiosoft.id/"
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", "query"], "rowLimit": 5000}).execute().get("rows", [])

klik = sum(r["clicks"] for r in rows)
tayang = sum(r["impressions"] for r in rows)
print(f"90 hari: {int(klik)} klik · {tayang:,} tayangan · CTR {klik / tayang * 100:.2f}%")

BAND = [(1, 3, "halaman atas (1-3)"), (4, 10, "halaman 1 (4-10)"), (11, 20, "halaman 2"),
        (21, 50, "halaman 3-5"), (51, 999, "lebih dalam")]
print("\ntayangan menurut posisi:")
for a, b, nama in BAND:
    grup = [r for r in rows if a <= r["position"] <= b]
    t = sum(r["impressions"] for r in grup)
    k = sum(r["clicks"] for r in grup)
    if t:
        print(f"   {nama:<20}{t:>9,} tayangan ({t / tayang * 100:>4.1f}%) · {int(k):>4} klik · "
              f"CTR {k / t * 100:>5.2f}%")

print("\nhalaman posisi <=10 tapi klik nol (yang bisa diperbaiki judulnya):")
per = []
for r in rows:
    per.append(r)
hal = defaultdict(lambda: {"t": 0, "k": 0, "p": 0.0, "n": 0, "q": ""})
for r in per:
    h = hal[r["keys"][0]]
    h["t"] += r["impressions"]
    h["k"] += r["clicks"]
    h["p"] += r["position"]
    h["n"] += 1
    if r["impressions"] > h.get("tmaks", 0):
        h["tmaks"] = r["impressions"]
        h["q"] = r["keys"][1]
calon = [(v["t"], v["k"], v["p"] / v["n"], k, v["q"]) for k, v in hal.items()
         if v["p"] / v["n"] <= 10 and v["k"] == 0 and v["t"] >= 50]
calon.sort(reverse=True)
for t, k, p, url, q in calon[:6]:
    print(f"   {t:>5} tayangan · pos {p:>4.1f} · «{q[:44]}» · {url.replace('https://studiosoft.id', '')[:44]}")
print(f"\njumlah halaman seperti itu: {len(calon)}")
