#!/usr/bin/env python3
"""TSLaw: cari properti GSC & GA4 untuk tslaw.id, lalu tarik performa 28 & 90 hari."""
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
SC = ["https://www.googleapis.com/auth/webmasters.readonly"]

print("=== 1. properti Search Console yang bisa diakses ===")
gsc = build("searchconsole", "v1", credentials=service_account.Credentials.from_service_account_file(KEY, scopes=SC),
            cache_discovery=False)
sites = gsc.sites().list().execute().get("siteEntry", [])
target = None
for s in sites:
    tanda = ""
    if "tslaw" in s["siteUrl"]:
        tanda = "   ← TSLaw"; target = s["siteUrl"]
    print(f"   {s['siteUrl']:<46} {s.get('permissionLevel')}{tanda}")

print("\n=== 2. properti GA4 yang bisa diakses ===")
adm = build("analyticsadmin", "v1beta",
            credentials=service_account.Credentials.from_service_account_file(
                KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]),
            cache_discovery=False)
props = []
try:
    for a in adm.accountSummaries().list().execute().get("accountSummaries", []):
        for p in a.get("propertySummaries", []):
            props.append((p["property"], p.get("displayName"), a.get("displayName")))
            print(f"   {p['property']:<28} {p.get('displayName')}  (akun: {a.get('displayName')})")
except Exception as e:
    print("   gagal:", str(e)[:160])

prop_tslaw = None
for pid, nama, akun in props:
    if nama and ("tslaw" in nama.lower() or "ts law" in nama.lower() or "tito" in nama.lower()):
        prop_tslaw = pid
print(f"\n   → properti TSLaw: {prop_tslaw or 'TIDAK DITEMUKAN'}")

if not target:
    print("\nGSC tidak punya properti tslaw.id untuk service account ini — data GSC tidak bisa ditarik.")
else:
    print(f"\n=== 3. GSC {target} ===")
    for label, mulai, akhir in (("28 hari (29 Agu–25 Sep)", "2026-08-29", "2026-09-25"),
                                ("90 hari (28 Jun–25 Sep)", "2026-06-28", "2026-09-25")):
        body = {"startDate": mulai, "endDate": akhir, "dimensions": ["date"], "rowLimit": 1}
        try:
            tot = gsc.searchanalytics().query(siteUrl=target, body={
                "startDate": mulai, "endDate": akhir, "dimensions": ["query"], "rowLimit": 1}).execute()
            # ringkasan agregat
            ring = gsc.searchanalytics().query(siteUrl=target, body={
                "startDate": mulai, "endDate": akhir, "dimensions": ["country"], "rowLimit": 1}).execute()
            rows = gsc.searchanalytics().query(siteUrl=target, body={
                "startDate": mulai, "endDate": akhir, "dimensions": ["page"], "rowLimit": 500}).execute().get("rows", [])
            klik = sum(r["clicks"] for r in rows); imp = sum(r["impressions"] for r in rows)
            print(f"\n  ── {label} ──")
            print(f"     klik {klik} | impresi {imp} | CTR {round(klik/imp*100, 2) if imp else 0}%")
            print("     halaman teratas:")
            for r in sorted(rows, key=lambda x: -x["impressions"])[:8]:
                print(f"       imp {r['impressions']:>5} | klik {r['clicks']:>3} | pos {round(r['position'],1):>5} | {r['keys'][0][:66]}")
            q = gsc.searchanalytics().query(siteUrl=target, body={
                "startDate": mulai, "endDate": akhir, "dimensions": ["query"], "rowLimit": 400}).execute().get("rows", [])
            print("     query teratas:")
            for r in sorted(q, key=lambda x: -x["impressions"])[:10]:
                print(f"       imp {r['impressions']:>5} | klik {r['clicks']:>3} | pos {round(r['position'],1):>5} | {r['keys'][0][:58]}")
        except Exception as e:
            print(f"  {label}: gagal — {str(e)[:140]}")

if prop_tslaw:
    print(f"\n=== 4. GA4 {prop_tslaw} ===")
    ga = build("analyticsdata", "v1beta",
               credentials=service_account.Credentials.from_service_account_file(
                   KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)
    for label, mulai, akhir in (("28 hari", "2026-08-29", "2026-09-25"), ("90 hari", "2026-06-28", "2026-09-25")):
        try:
            r = ga.properties().runReport(property=prop_tslaw, body={
                "dateRanges": [{"startDate": mulai, "endDate": akhir}],
                "metrics": [{"name": "sessions"}, {"name": "totalUsers"}, {"name": "screenPageViews"},
                            {"name": "keyEvents"}, {"name": "averageSessionDuration"}],
                "dimensions": [{"name": "sessionDefaultChannelGroup"}], "limit": 12}).execute()
            print(f"\n  ── {label} ──")
            for row in r.get("rows", []):
                ch = row["dimensionValues"][0]["value"]
                v = [x["value"] for x in row["metricValues"]]
                print(f"     {ch:<20} sesi {v[0]:>5} | pengguna {v[1]:>5} | halaman {v[2]:>5} | "
                      f"kejadian {v[3]:>4} | durasi {round(float(v[4]))}s")
        except Exception as e:
            print(f"  {label}: gagal — {str(e)[:160]}")
