#!/usr/bin/env python3
"""Cari artikel StudioSoft yang NOL impresi di GSC 90 hari — kandidat yang perlu ditangani."""
import base64, html, json, os, re, time, urllib.request
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
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)
e = date.today() - timedelta(days=2)
a, b = (e - timedelta(days=89)).isoformat(), e.isoformat()


def api(path):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    r = urllib.request.Request(S + path, headers=h)
    err = None
    for _ in range(4):
        try:
            with urllib.request.urlopen(r, timeout=240) as x:
                return json.loads(x.read())
        except Exception as ex:
            err = ex; time.sleep(5)
    print("  gagal:", str(err)[:70]); return []


imp = {}
for r in gsc.searchanalytics().query(siteUrl=S + "/", body={"startDate": a, "endDate": b, "dimensions": ["page"],
                                                            "rowLimit": 2000}).execute().get("rows", []):
    imp[r["keys"][0].rstrip("/")] = int(r["impressions"])
print(f"halaman yang punya impresi (90d): {len(imp)}")

posts, page = [], 1
while True:
    d = api(f"/wp-json/wp/v2/posts?per_page=100&page={page}&context=edit&_fields=id,link,title,date,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

nol, baru = [], []
for p in posts:
    if p["link"].rstrip("/") in imp:
        continue
    umur = (date.today() - date.fromisoformat(p["date"][:10])).days
    raw = p["content"]["raw"] if isinstance(p["content"], dict) else ""
    kata = len(html.unescape(re.sub(r"<[^>]+>", " ", raw)).split())
    item = {"id": p["id"], "judul": html.unescape(p["title"]["rendered"]), "link": p["link"],
            "tgl": p["date"][:10], "umur": umur, "kata": kata}
    (baru if umur < 30 else nol).append(item)

json.dump({"nol_impresi": nol, "baru": baru}, open("ss_nol_impresi.json", "w"), indent=1, ensure_ascii=False)
print(f"\ntotal artikel publish: {len(posts)}")
print(f"NOL impresi & umur >=30 hari : {len(nol)}   ← ini yang perlu ditangani")
print(f"NOL impresi & umur <30 hari  : {len(baru)}   (mungkin belum terindeks, wajar)\n")

print("=== yang >=30 hari & nol impresi (40 terbaru) ===")
for x in sorted(nol, key=lambda y: y["tgl"], reverse=True)[:40]:
    print(f"  {x['tgl']} | {x['umur']:>3}h | {x['kata']:>5} kata | #{x['id']:>5} | {x['judul'][:58]}")

print("\nsebaran umur:")
for pita in ((30, 60), (60, 120), (120, 365), (365, 9999)):
    n = [x for x in nol if pita[0] <= x["umur"] < pita[1]]
    print(f"  umur {pita[0]}-{pita[1] if pita[1]<9999 else '+'} hari: {len(n)} artikel")
print("\nsebaran panjang:")
for pita in ((0, 600), (600, 1000), (1000, 99999)):
    n = [x for x in nol if pita[0] <= x["kata"] < pita[1]]
    print(f"  {pita[0]}-{pita[1] if pita[1]<99999 else '+'} kata: {len(n)} artikel")
