#!/usr/bin/env python3
"""Cek key events + link Google Ads GA4 via REST langsung, lalu kesiapan halaman pendarat StudioSoft."""
import json, os, re, time, urllib.request, urllib.error
from google.auth.transport.requests import Request
from google.oauth2 import service_account

creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/analytics.readonly"])
creds.refresh(Request())
H = {"Authorization": f"Bearer {creds.token}"}


def rest(url):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=H), timeout=60) as x:
            return x.status, json.loads(x.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:300]


P = "properties/478760195"
print("=== KEY EVENTS (konversi) ===")
st, r = rest(f"https://analyticsadmin.googleapis.com/v1beta/{P}/keyEvents")
print("  status:", st)
if isinstance(r, dict):
    ke = r.get("keyEvents", [])
    print(f"  jumlah: {len(ke)}")
    for k in ke:
        print("   -", k.get("eventName"), "|", k.get("countingMethod"))
    if not ke:
        print("   (TIDAK ADA key event — belum ada konversi yang didefinisikan)")

print("\n=== LINK GOOGLE ADS ===")
st, r = rest(f"https://analyticsadmin.googleapis.com/v1beta/{P}/googleAdsLinks")
print("  status:", st)
if isinstance(r, dict):
    links = r.get("googleAdsLinks", [])
    print(f"  jumlah: {len(links)}")
    for l in links:
        print("   -", json.dumps(l, ensure_ascii=False)[:220])
    if not links:
        print("   (GA4 belum tersambung ke akun Google Ads mana pun)")

print("\n=== DATA STREAM ===")
st, r = rest(f"https://analyticsadmin.googleapis.com/v1beta/{P}/dataStreams")
if isinstance(r, dict):
    for ds in r.get("dataStreams", []):
        w = ds.get("webStreamData", {})
        print(f"  {ds.get('displayName')} | {w.get('measurementId')} | {w.get('defaultUri')}")

print("\n=== KESIAPAN HALAMAN PENDARAT ===")
HAL = ["/", "/jasa-seo-professional/", "/layanan/", "/jasa-pembuatan-website/", "/jasa-seo-surabaya/",
       "/digital-marketing-surabaya/", "/kontak/"]
UA = {"User-Agent": "Mozilla/5.0"}
for u in HAL:
    t0 = time.time()
    try:
        r = urllib.request.Request("https://studiosoft.id" + u, headers=UA)
        resp = urllib.request.urlopen(r, timeout=90)
        h = resp.read().decode("utf-8", "replace")
        dt = time.time() - t0
        wa = len(re.findall(r"wa\.me|api\.whatsapp|whatsapp\.com", h))
        form = len(re.findall(r"<form", h))
        tel = len(re.findall(r"tel:", h))
        ttl = re.search(r"<title>(.*?)</title>", h, re.S)
        cta = len(re.findall(r"(konsultasi|hubungi|gratis|penawaran|hubungin)", h, re.I))
        print(f"  {u:<28} {dt:>5.2f}s | WA:{wa:>2} form:{form} tel:{tel} | kata CTA:{cta:>3} | {(ttl.group(1)[:52] if ttl else '-')}")
    except urllib.error.HTTPError as e:
        print(f"  {u:<28} HTTP {e.code}")
    except Exception as e:
        print(f"  {u:<28} GAGAL {str(e)[:50]}")
