#!/usr/bin/env python3
"""Cek klinikmetamorf.com: situs, akses WP, properti GSC/GA4."""
import base64, json, os, time, urllib.request, urllib.error
from google.oauth2 import service_account
from googleapiclient.discovery import build

SITE = "https://klinikmetamorf.com"
UA = {"User-Agent": "Mozilla/5.0"}
AUTH = base64.b64encode(b"bambangbot:whWA hVlW omQk 9FSL 8rkz VMHy").decode()

print("=== 1. Status situs ===")
for u in ("https://klinikmetamorf.com/", "https://www.klinikmetamorf.com/"):
    try:
        t0 = time.time()
        r = urllib.request.Request(u, headers=UA)
        resp = urllib.request.urlopen(r, timeout=60)
        body = resp.read()
        print(f"  {resp.status} | {time.time()-t0:.2f}s | {len(body)//1024} KB | {u}")
        print(f"     cf-cache: {resp.headers.get('cf-cache-status','-')} | server: {resp.headers.get('server','-')}")
    except urllib.error.HTTPError as e:
        print(f"  {e.code} | {e.headers.get('location','-')} | {u}")
    except Exception as e:
        print(f"  ERR {str(e)[:60]} | {u}")

print("\n=== 2. Akses WordPress REST ===")
def wp(path):
    r = urllib.request.Request(SITE + path, headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=90) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"__err": e.code, "pesan": e.read().decode()[:150]}
        except Exception as e:
            time.sleep(3)
    return {"__err": "gagal"}

info = wp("/wp-json")
if isinstance(info, dict) and "__err" not in info:
    print(f"  nama situs : {info.get('name')} | deskripsi: {str(info.get('description'))[:60]}")
    print(f"  timezone   : {info.get('timezone_string')} | gmt_offset: {info.get('gmt_offset')}")
    print(f"  plugin Yoast di namespace: {'yoast/v1' in (info.get('namespaces') or [])}")
posts = wp("/wp-json/wp/v2/posts?per_page=5&_fields=id,title,date,link")
if isinstance(posts, list):
    print(f"  5 artikel terakhir:")
    for p in posts:
        print(f"     {p['date'][:10]} | #{p['id']} {p['title']['rendered'][:56]}")
else:
    print("  posts:", posts)

users = wp("/wp-json/wp/v2/users/me?_fields=id,name,roles")
print("  user bot:", json.dumps(users, ensure_ascii=False)[:140] if isinstance(users, dict) else users)

print("\n=== 3. Properti Google (service account) ===")
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)
sites = [s["siteUrl"] for s in gsc.sites().list().execute().get("siteEntry", [])]
print("  GSC punya metamorf?", [s for s in sites if "metamorf" in s.lower()] or "TIDAK ADA — belum ditambahkan")
admin = build("analyticsadmin", "v1beta", credentials=creds, cache_discovery=False)
found = []
for acc in admin.accounts().list().execute().get("accounts", []):
    for p in admin.properties().list(filter=f"parent:{acc['name']}").execute().get("properties", []):
        if "metamorf" in json.dumps(p).lower():
            found.append((p["name"], p.get("displayName")))
print("  GA4 properti metamorf:", found or "TIDAK ADA")
