#!/usr/bin/env python3
"""DAS: analisis menyeluruh dari GSC saja.
- brand vs non-brand (28d vs 28d sebelumnya)
- sebaran pita posisi + CTR per pita
- halaman: pemenang & yang kehilangan
- peluang: halaman 1 tapi nol klik, posisi 4-20, kata kunci terbaik per pita
- perangkat & negara
"""
import os, re, json
from collections import Counter
from google.oauth2 import service_account
from googleapiclient.discovery import build

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
WS = "/home/mantapman/.hermes/profiles/atun/workspace"
SITE = "https://dasindonesia.com/"
gsc = build("searchconsole", "v1", credentials=service_account.Credentials.from_service_account_file(
    KEY, scopes=["https://www.googleapis.com/auth/webmasters.readonly"]), cache_discovery=False)

P_LAMA = ("2026-08-01", "2026-08-28")
P_BARU = ("2026-08-29", "2026-09-25")
BRAND = re.compile(r"\bdas\b|das indonesia|bengkel das|das bengkel", re.I)


def q(dims, a, b, limit=5000, extra=None):
    body = {"startDate": a, "endDate": b, "dimensions": list(dims), "rowLimit": limit}
    if extra:
        body.update(extra)
    return gsc.searchanalytics().query(siteUrl=SITE, body=body).execute().get("rows", [])


print("=== 1. brand vs non-brand ===")
for label, (a, b) in (("28d sebelumnya", P_LAMA), ("28d terakhir", P_BARU)):
    rows = q(["query"], a, b)
    brand = [r for r in rows if BRAND.search(r["keys"][0])]
    non = [r for r in rows if not BRAND.search(r["keys"][0])]
    def s(rs, k):
        return sum(r[k] for r in rs)
    imp_b, klik_b = s(brand, "impressions"), s(brand, "clicks")
    imp_n, klik_n = s(non, "impressions"), s(non, "clicks")
    print(f"\n  {label}")
    print(f"     brand     : {len(brand):>4} query | {imp_b:>6} impresi | {klik_b:>4} klik | CTR {round(klik_b/imp_b*100,2) if imp_b else 0}%")
    print(f"     non-brand : {len(non):>4} query | {imp_n:>6} impresi | {klik_n:>4} klik | CTR {round(klik_n/imp_n*100,2) if imp_n else 0}%")

print("\n=== 2. sebaran pita posisi (query) ===")
PITA = [(1, 3, "1-3"), (4, 10, "4-10"), (11, 20, "11-20"), (21, 50, "21-50"), (51, 999, "51+")]
for label, (a, b) in (("28d sebelumnya", P_LAMA), ("28d terakhir", P_BARU)):
    rows = q(["query"], a, b)
    print(f"\n  {label} ({len(rows)} query)")
    for lo, hi, nama in PITA:
        sel = [r for r in rows if lo <= r["position"] <= hi]
        imp = sum(r["impressions"] for r in sel); klik = sum(r["clicks"] for r in sel)
        print(f"     pos {nama:<6} {len(sel):>4} query | {imp:>6} impresi | {klik:>4} klik | CTR {round(klik/imp*100,2) if imp else 0}%")

print("\n=== 3. halaman: pemenang 28 hari terakhir ===")
rows = q(["page"], *P_BARU)
for r in sorted(rows, key=lambda x: -x["clicks"])[:10]:
    print(f"   klik {r['clicks']:>3} | imp {r['impressions']:>5} | CTR {round(r['ctr']*100,2):>5}% | pos {round(r['position'],1):>5} | {r['keys'][0].replace('https://dasindonesia.com','')[:54]}")

print("\n=== 4. peluang A: sudah halaman 1 tapi nol klik (impresi >= 5) ===")
rows = q(["query", "page"], *P_BARU)
nol = [r for r in rows if r["position"] <= 10 and r["clicks"] == 0 and r["impressions"] >= 5]
nol.sort(key=lambda x: -x["impressions"])
for r in nol[:14]:
    print(f"   imp {r['impressions']:>4} | pos {round(r['position'],1):>5} | {r['keys'][0][:52]:<54} {r['keys'][1].replace('https://dasindonesia.com','')[:38]}")

print("\n=== 5. peluang B: posisi 4-20 (bisa didorong ke atas) ===")
push = [r for r in rows if 4 <= r["position"] <= 20 and r["impressions"] >= 5]
push.sort(key=lambda x: -x["impressions"])
for r in push[:14]:
    print(f"   imp {r['impressions']:>4} | klik {r['clicks']:>2} | pos {round(r['position'],1):>5} | {r['keys'][0][:52]:<54} {r['keys'][1].replace('https://dasindonesia.com','')[:34]}")

print("\n=== 6. perangkat & negara (28d terakhir) ===")
for dim in ("device", "country"):
    rows = q([dim], *P_BARU)
    tot = sum(r["impressions"] for r in rows)
    for r in sorted(rows, key=lambda x: -x["impressions"])[:5]:
        print(f"   {dim:<8} {r['keys'][0]:<12} imp {r['impressions']:>6} ({round(r['impressions']/tot*100)}%) klik {r['clicks']}")

print("\n=== 7. query baru yang muncul di 28d terakhir (tidak ada di periode sebelumnya) ===")
lama = {r["keys"][0] for r in q(["query"], *P_LAMA)}
baru_rows = q(["query"], *P_BARU)
baru = [r for r in baru_rows if r["keys"][0] not in lama]
baru.sort(key=lambda x: -x["impressions"])
print(f"   {len(baru)} query baru")
for r in baru[:10]:
    print(f"   imp {r['impressions']:>4} | klik {r['clicks']} | pos {round(r['position'],1):>5} | {r['keys'][0][:56]}")
