#!/usr/bin/env python3
"""Monitor harian StudioSoft (data nyata, tanpa angka karangan):
- GSC: 7 hari terakhir vs 7 hari sebelumnya (klik, tayangan, posisi)
- kueri ber-tayangan tapi nol klik
- kueri baru yang muncul
- kesehatan jadwal terbit (hari kosong / ganda / sisa persediaan)
"""
import base64, json, os, subprocess, sys
from datetime import date, timedelta

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

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "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=6)
p_awal, p_akhir = awal - timedelta(days=7), awal - timedelta(days=1)


def ambil(a, b, dims=("query",)):
    return gsc.searchanalytics().query(siteUrl=S + "/", body={
        "startDate": a.isoformat(), "endDate": b.isoformat(), "dimensions": list(dims),
        "rowLimit": 1000}).execute().get("rows", [])


def total(a, b):
    r = gsc.searchanalytics().query(siteUrl=S + "/", body={
        "startDate": a.isoformat(), "endDate": b.isoformat()}).execute().get("rows", [])
    if not r:
        return 0, 0, 0.0
    x = r[0]
    return int(x["clicks"]), int(x["impressions"]), round(x["position"], 1)


k1, t1, p1 = total(awal, akhir)
k0, t0, p0 = total(p_awal, p_akhir)
print(f"STUDIOSOFT — monitor {awal} s/d {akhir} (GSC, data nyata)")
print(f"  klik      : {k1} ({k1 - k0:+d} vs pekan sebelumnya: {k0})")
print(f"  tayangan  : {t1} ({t1 - t0:+d} vs {t0})")
print(f"  posisi    : {p1} ({round(p1 - p0, 1):+} vs {p0})")

kini = {r["keys"][0]: (r["clicks"], r["impressions"], round(r["position"], 1)) for r in ambil(awal, akhir)}
dulu = {r["keys"][0]: (r["clicks"], r["impressions"], round(r["position"], 1)) for r in ambil(p_awal, p_akhir)}

naik = [(q, kini[q][0], dulu.get(q, (0, 0, 0))[0]) for q in kini if kini[q][0] > dulu.get(q, (0, 0, 0))[0]]
if naik:
    print("\n  kueri yang mulai menghasilkan klik:")
    for q, a, b in sorted(naik, key=lambda x: -(x[1] - x[2]))[:5]:
        print(f"    «{q}» {b} → {a} klik")

nol = sorted(((v[1], q, v[2]) for q, v in kini.items() if v[0] == 0 and v[1] >= 50), reverse=True)
if nol:
    print("\n  kueri bertayangan tapi nol klik (>=50 tayangan):")
    for t, q, pos in nol[:5]:
        print(f"    «{q}» {t} tayangan · posisi {pos}")

baru = [q for q in kini if q not in dulu and kini[q][1] >= 20]
if baru:
    print(f"\n  kueri baru (>=20 tayangan): {len(baru)} — " + ", ".join(f"«{q}»" for q in baru[:6]))

print("\n  jadwal terbit:")
r = subprocess.run([sys.executable, f"{WS}/ss_jadwal_cek.py"], capture_output=True, text=True, cwd=WS)
for baris in r.stdout.strip().splitlines():
    print("    " + baris)
if r.returncode != 0:
    print("    ⚠ jadwal perlu ditambah")
