#!/usr/bin/env python3
"""TSLaw lanjutan: kecepatan respons (beberapa kali), halaman sampah, judul/meta beranda,
kejadian GA4, dan overflow di ponsel."""
import base64, json, os, time, urllib.request, urllib.error
from google.oauth2 import service_account
from googleapiclient.discovery import build

DOM = "tslaw.id"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")

print("=== 1. kecepatan (5 kali percobaan) ===")
for i in range(5):
    for u in (f"https://{DOM}/", f"https://www.{DOM}/"):
        t0 = time.time()
        try:
            r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60)
            b = r.read()
            print(f"  {i+1}. {u:<28} {r.status} | total {round(time.time()-t0,2)}s | TTFB {round(r.headers.get('cf-mitigated') and 0 or 0,0)} "
                  f"| cf={r.headers.get('cf-cache-status')} | age={r.headers.get('age')} | {len(b)//1024} KB")
        except Exception as e:
            print(f"  {i+1}. {u:<28} GAGAL {str(e)[:50]} | {round(time.time()-t0,2)}s")

print("\n=== 2. halaman sisa yang seharusnya tidak ada ===")
for u in ("/sample-page/", "/hello-world/", "/?p=1", "/wp-sitemap.xml"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}{u}", headers=UA), timeout=45)
        isi = r.read().decode("utf-8", "replace")
        sisa = "KOSONG/minim" if len(isi) < 600 else f"{len(isi)//1024} KB"
        print(f"  {r.status} | {u:<18} {sisa}")
    except urllib.error.HTTPError as e:
        print(f"  {e.code} | {u}")

print("\n=== 3. judul & meta beranda ===")
h = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
import re
t = re.search(r"<title>(.*?)</title>", h, re.S)
md = re.search(r'<meta name="description" content="([^"]*)"', h)
og = re.search(r'<meta property="og:title" content="([^"]*)"', h)
can = re.search(r'<link rel="canonical" href="([^"]*)"', h)
print("  judul     :", (t.group(1)[:90] if t else "-"))
print("  meta desc :", (f"({len(md.group(1))} char) {md.group(1)[:90]}" if md else "TIDAK ADA"))
print("  og:title  :", (og.group(1)[:80] if og else "-"))
print("  canonical :", (can.group(1) if can else "-"))
print("  jumlah kata halaman depan:", len([w for w in re.split(r"\s+", re.sub(r"<[^>]+>", " ", h)) if w]))

print("\n=== 4. kejadian GA4 (90 hari) ===")
try:
    ga = build("analyticsdata", "v1beta",
               credentials=service_account.Credentials.from_service_account_file(
                   KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)
    r = ga.properties().runReport(property="properties/537990618", body={
        "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
        "dimensions": [{"name": "eventName"}], "metrics": [{"name": "eventCount"}],
        "limit": 25, "orderBys": [{"metric": {"metricName": "eventCount"}, "desc": True}]}).execute()
    for row in r.get("rows", []):
        print(f"   {row['dimensionValues'][0]['value']:<26} {row['metricValues'][0]['value']}")
except Exception as e:
    print("   gagal:", str(e)[:150])

print("\n=== 5. halaman pendaratan teratas (GA4 90 hari) ===")
try:
    r = ga.properties().runReport(property="properties/537990618", body={
        "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
        "dimensions": [{"name": "landingPagePlusQueryString"}],
        "metrics": [{"name": "sessions"}, {"name": "keyEvents"}, {"name": "userEngagementDuration"}],
        "limit": 12, "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]}).execute()
    for row in r.get("rows", []):
        lp = row["dimensionValues"][0]["value"]
        v = [x["value"] for x in row["metricValues"]]
        print(f"   sesi {v[0]:>4} | kejadian {v[1]:>2} | {round(float(v[2])/max(int(v[0]),1)):>4}s | {lp[:60]}")
except Exception as e:
    print("   gagal:", str(e)[:150])
