#!/usr/bin/env python3
"""DAS: GSC + GA4 lengkap. Sekaligus cek apakah ada jalur Google Ads (developer token/OAuth) di workspace."""
import os, re, json, glob

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
print("=== 1. konfigurasi & berkas DAS ===")
for f in sorted(glob.glob(f"{WS}/cfg_das*")) + [f for f in glob.glob(f"{WS}/*das*ads*")] + [f"{WS}/ss_ads_audit.py"]:
    if os.path.exists(f):
        print(f"   {os.path.basename(f):<34} {os.path.getsize(f)} byte")

print("\n=== 2. apakah ada kredensial Google Ads / Keyword Planner? ===")
kandidat = []
for pola in ("*ads*", "*google_ads*", "*keyword_plan*", "*.env"):
    kandidat += glob.glob(f"{WS}/{pola}") + glob.glob(f"/home/mantapman/.hermes/profiles/atun/{pola}")
for f in sorted(set(kandidat))[:20]:
    if os.path.isfile(f):
        isi = open(f, errors="replace").read()[:400]
        petunjuk = [k for k in ("developer", "developerToken", "DEVELOPER_TOKEN", "login-customer-id",
                                "oauth", "ads.googleapis", "refresh_token") if k.lower() in isi.lower()]
        print(f"   {os.path.basename(f):<34} {'→ ' + ', '.join(petunjuk) if petunjuk else '(tidak ada penanda Ads)'}")

print("\n=== 3. apa yang dipakai ss_ads_audit.py (script audit Ads StudioSoft) ===")
p = f"{WS}/ss_ads_audit.py"
if os.path.exists(p):
    isi = open(p, errors="replace").read()
    for baris in isi.splitlines()[:30]:
        if re.search(r"api|token|key|url|property|P =", baris, re.I):
            print("   ", baris.strip()[:130])

print("\n=== 4. properti Google yang bisa diakses service account (GSC & GA4) ===")
from google.oauth2 import service_account
from googleapiclient.discovery import build
KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
gsc = build("searchconsole", "v1", credentials=service_account.Credentials.from_service_account_file(
    KEY, scopes=["https://www.googleapis.com/auth/webmasters.readonly"]), cache_discovery=False)
for s in gsc.sites().list().execute().get("siteEntry", []):
    if "das" in s["siteUrl"].lower():
        print(f"   GSC  : {s['siteUrl']} ({s.get('permissionLevel')})")
adm = build("analyticsadmin", "v1beta", credentials=service_account.Credentials.from_service_account_file(
    KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)
for a in adm.accountSummaries().list().execute().get("accountSummaries", []):
    if "das" in (a.get("displayName") or "").lower():
        for pr in a.get("propertySummaries", []):
            print(f"   GA4  : {pr['property']} → {pr.get('displayName')}")
