#!/usr/bin/env python3
"""Hitung apa yang dibutuhkan StudioSoft untuk mencapai 180 klik/28 hari, dan kandidat terdekat."""
import os
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)
AWAL28 = AKHIR - timedelta(days=27)
AWAL90 = AKHIR - timedelta(days=89)


def tarik(awal, dimensi):
    return gsc.searchanalytics().query(siteUrl=SITUS, body={
        "startDate": awal.isoformat(), "endDate": AKHIR.isoformat(),
        "dimensions": dimensi, "rowLimit": 5000}).execute().get("rows", [])


r28 = tarik(AWAL28, ["query"])
k28 = sum(r["clicks"] for r in r28)
t28 = sum(r["impressions"] for r in r28)
print(f"28 hari: {int(k28)} klik · {t28:,} tayangan · CTR {k28 / t28 * 100:.2f}%")

TARGET = 180
print(f"\ntarget GSC: {TARGET} klik/28 hari → butuh tambahan {TARGET - int(k28)} klik "
      f"({TARGET / max(k28, 1):.1f}× dari sekarang)")

# kebutuhan tayangan di halaman 1 (asumsi CTR 2,3% seperti sekarang di posisi <=10)
ctr_atas = 0.023
butuh_tayang_atas = TARGET / ctr_atas
print(f"\nkalau CTR halaman 1 tetap 2,3%: butuh {butuh_tayang_atas:,.0f} tayangan di posisi <=10")

r90 = tarik(AWAL90, ["query"])
atas = sum(x["impressions"] for x in r90 if x["position"] <= 10) / 3   # rata-rata per 28 hari
print(f"tayangan posisi <=10 sekarang (rata-rata 28 hari): {atas:,.0f} "
      f"→ perlu naik {butuh_tayang_atas / max(atas, 1):.1f}×")

print("\nkueri posisi 11-30 dengan tayangan terbanyak (kandidat didorong ke halaman 1):")
kand = [x for x in r90 if 10 < x["position"] <= 30 and x["impressions"] >= 15]
kand.sort(key=lambda x: -x["impressions"])
total_potensi = 0
for x in kand[:12]:
    pot = x["impressions"] / 3 * ctr_atas     # perkiraan klik/28 hari kalau naik ke halaman 1
    total_potensi += pot
    print(f"   {int(x['impressions'] / 3):>4} tayang/28h · pos {x['position']:>5.1f} · "
          f"potensi +{pot:>4.1f} klik · «{x['keys'][0][:44]}»")
print(f"\npotensi gabungan 12 kueri itu: +{total_potensi:.0f} klik/28 hari "
      f"(cukup untuk {total_potensi / max(TARGET - int(k28), 1) * 100:.0f}% dari kebutuhan)")
