#!/usr/bin/env python3
"""GA4 DAS + jumlah query GSC per minggu (diagnosa penyempitan visibilitas)."""
import os
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

creds = service_account.Credentials.from_service_account_file(os.path.expanduser("~/.hermes/gsc_service_account.json"),
                                                              scopes=["https://www.googleapis.com/auth/webmasters.readonly",
                                                                      "https://www.googleapis.com/auth/analytics.readonly"])
gsc = build("webmasters", "v3", credentials=creds, cache_discovery=False)
data = build("analyticsdata", "v1beta", credentials=creds, cache_discovery=False)

S = "https://dasindonesia.com/"
PROP = "properties/443064659"
e = date.today() - timedelta(days=2)

print("=== GSC: jumlah query & halaman per minggu (apakah ruang tampil menyempit?) ===")
print(f"{'minggu':<24} {'query':>6} {'halaman':>8} {'impresi':>8} {'klik':>5} {'pos rata2':>9}")
for i in range(10):
    en = e - timedelta(days=7 * i)
    st = en - timedelta(days=6)
    b = {"startDate": st.isoformat(), "endDate": en.isoformat(), "rowLimit": 1}
    tot = gsc.searchanalytics().query(siteUrl=S, body=dict(b, dimensions=[])).execute().get("rows", [])
    qs = gsc.searchanalytics().query(siteUrl=S, body=dict(b, dimensions=["query"], rowLimit=5000)).execute().get("rows", [])
    pgs = gsc.searchanalytics().query(siteUrl=S, body=dict(b, dimensions=["page"], rowLimit=2000)).execute().get("rows", [])
    imp = int(tot[0]["impressions"]) if tot else 0
    kl = int(tot[0]["clicks"]) if tot else 0
    pos = tot[0]["position"] if tot else 0
    print(f"{st}→{en:<10} {len(qs):>6} {len(pgs):>8} {imp:>8} {kl:>5} {pos:>9.1f}")

print("\n=== GA4 DAS: 28 hari terakhir vs 28 hari sebelumnya ===")
def rep(a, b, dims, mets, limit=10, order=True):
    body = {"dateRanges": [{"startDate": a, "endDate": b}],
            "metrics": [{"name": m} for m in mets], "limit": limit}
    if dims:
        body["dimensions"] = [{"name": d} for d in dims]
        if order:
            body["orderBys"] = [{"metric": {"metricName": mets[0]}, "desc": True}]
    return data.properties().runReport(property=PROP, body=body).execute()

a2, b2 = (e - timedelta(days=27)).isoformat(), e.isoformat()
a1, b1 = (e - timedelta(days=55)).isoformat(), (e - timedelta(days=28)).isoformat()
for label, (a, b) in (("28d kini", (a2, b2)), ("28d lalu", (a1, b1))):
    r = rep(a, b, [], ["sessions", "totalUsers", "screenPageViews", "engagementRate"])
    v = [m["value"] for m in r["rows"][0]["metricValues"]] if r.get("rows") else ["0"] * 4
    print(f"  {label}: sesi {v[0]} | user {v[1]} | pageview {v[2]} | engagement {float(v[3])*100:.1f}%")

print("\n  channel 28d kini:")
for row in rep(a2, b2, ["sessionDefaultChannelGroup"], ["sessions"]).get("rows", []):
    print(f"    {row['dimensionValues'][0]['value']:<22} {row['metricValues'][0]['value']}")

print("\n  halaman masuk 28d kini:")
for row in rep(a2, b2, ["landingPagePlusQueryString"], ["sessions", "screenPageViews"]).get("rows", []):
    print(f"    {row['metricValues'][0]['value']:>3} sesi | {row['dimensionValues'][0]['value'][:60]}")

print("\n  konversi/aksi (28d kini):")
for row in rep(a2, b2, ["eventName"], ["eventCount"]).get("rows", [])[:10]:
    print(f"    {row['dimensionValues'][0]['value']:<26} {row['metricValues'][0]['value']}")
