#!/usr/bin/env python3
"""DAS: GSC + GA4 (dasindonesia.com) + GA4 Keyword Hero (data kata kunci)."""
import os, json, re
from google.oauth2 import service_account
from googleapiclient.discovery import build

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
GSC_SITE = "https://dasindonesia.com/"
GA = "properties/443064659"
KH = "properties/477795602"
CRE = service_account.Credentials.from_service_account_file
RO = ["https://www.googleapis.com/auth/analytics.readonly"]

gsc = build("searchconsole", "v1", credentials=CRE(KEY, scopes=["https://www.googleapis.com/auth/webmasters.readonly"]),
            cache_discovery=False)
ga = build("analyticsdata", "v1beta", credentials=CRE(KEY, scopes=RO), cache_discovery=False)
adm = build("analyticsadmin", "v1beta", credentials=CRE(KEY, scopes=RO), cache_discovery=False)

print("=" * 90)
print("=== 1. GSC dasindonesia.com ===")
for label, a, b in (("28 hari", "2026-08-29", "2026-09-25"), ("28 hari sebelumnya", "2026-08-01", "2026-08-28"),
                    ("90 hari", "2026-06-28", "2026-09-25")):
    try:
        rows = gsc.searchanalytics().query(siteUrl=GSC_SITE, body={
            "startDate": a, "endDate": b, "dimensions": ["page"], "rowLimit": 5000}).execute().get("rows", [])
        klik = sum(r["clicks"] for r in rows); imp = sum(r["impressions"] for r in rows)
        print(f"   {label:<20} {klik:>5} klik | {imp:>7} impresi | CTR {round(klik/imp*100,2) if imp else 0}%")
    except Exception as e:
        print(f"   {label}: gagal {str(e)[:70]}")

rows = gsc.searchanalytics().query(siteUrl=GSC_SITE, body={
    "startDate": "2026-08-29", "endDate": "2026-09-25", "dimensions": ["query"], "rowLimit": 3000}).execute().get("rows", [])
print(f"\n   query 28 hari: {len(rows)}")
for r in sorted(rows, key=lambda x: -x["impressions"])[:12]:
    print(f"      imp {r['impressions']:>5} | klik {r['clicks']:>3} | pos {round(r['position'],1):>5} | {r['keys'][0][:56]}")

print("\n" + "=" * 90)
print("=== 2. GA4 dasindonesia.com (443064659) ===")
def rep(prop, dims, mets, a, b, limit=10, urut=None):
    body = {"dateRanges": [{"startDate": a, "endDate": b}],
            "dimensions": [{"name": d} for d in dims], "metrics": [{"name": m} for m in mets], "limit": limit}
    if urut:
        body["orderBys"] = [{"metric": {"metricName": urut}, "desc": True}]
    return ga.properties().runReport(property=prop, body=body).execute().get("rows", [])

for label, a, b in (("28 hari", "2026-08-29", "2026-09-25"), ("90 hari", "2026-06-28", "2026-09-25")):
    r = rep(GA, [], ["sessions", "totalUsers", "screenPageViews", "keyEvents", "averageSessionDuration", "engagementRate"], a, b, 1)
    if r:
        v = [x["value"] for x in r[0]["metricValues"]]
        print(f"   {label:<8} sesi {v[0]:>5} | pengguna {v[1]:>5} | halaman {v[2]:>6} | kejadian kunci {v[3]:>3} | "
              f"durasi {round(float(v[4]))}s | engagement {round(float(v[5])*100)}%")
print("   kanal (28 hari):")
for row in rep(GA, ["sessionDefaultChannelGroup"], ["sessions", "keyEvents"], "2026-08-29", "2026-09-25", 8, "sessions"):
    print(f"      {row['dimensionValues'][0]['value'][:20]:<22} sesi {row['metricValues'][0]['value']:>4} | kunci {row['metricValues'][1]['value']}")
print("   halaman pendaratan (28 hari):")
for row in rep(GA, ["landingPagePlusQueryString"], ["sessions", "userEngagementDuration"], "2026-08-29", "2026-09-25", 8, "sessions"):
    d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
    print(f"      sesi {v[0]:>4} | {round(float(v[1])/max(int(v[0]),1)):>4}s | {d[:54]}")
print("   kejadian (28 hari):")
for row in rep(GA, ["eventName"], ["eventCount"], "2026-08-29", "2026-09-25", 12, "eventCount"):
    print(f"      {row['dimensionValues'][0]['value'][:28]:<30} {row['metricValues'][0]['value']}")

print("\n" + "=" * 90)
print("=== 3. GA4 Keyword Hero (477795602) — data kata kunci ===")
try:
    cd = adm.properties().customDimensions().list(parent=KH).execute().get("customDimensions", [])
    print(f"   {len(cd)} dimensi kustom:")
    for d in cd:
        print(f"      {d.get('parameterName')} | {d.get('displayName')} | {d.get('scope')}")
except Exception as e:
    print("   gagal baca dimensi:", str(e)[:100])

r = rep(KH, [], ["sessions", "totalUsers", "keyEvents"], "2026-08-29", "2026-09-25", 1)
if r:
    v = [x["value"] for x in r[0]["metricValues"]]
    print(f"   sesi {v[0]} | pengguna {v[1]} | kejadian kunci {v[2]}")
for dim in ("sessionKeywordHeroKeyword", "keywordHeroKeyword", "eventKeywordHeroKeyword"):
    try:
        rows = rep(KH, [dim], ["sessions"], "2026-08-29", "2026-09-25", 12, "sessions")
        if rows:
            print(f"   dimensi '{dim}' → {len(rows)} baris")
            for row in rows[:10]:
                print(f"      sesi {row['metricValues'][0]['value']:>3} | {row['dimensionValues'][0]['value'][:60]}")
            break
    except Exception as e:
        print(f"   dimensi '{dim}': {str(e)[:70]}")
