#!/usr/bin/env python3
"""Petakan properti GSC + GA4 yang bisa diakses, untuk menyusun konfigurasi per klien."""
import json, urllib.request, urllib.error

TOKEN = "/home/mantapman/.hermes/profiles/atun/workspace/seo-oauth/google_token_atun.json"
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
c = Credentials.from_authorized_user_file(TOKEN)
if c.expired and c.refresh_token:
    c.refresh(Request()); open(TOKEN, "w").write(c.to_json())
H = {"Authorization": f"Bearer {c.token}", "Content-Type": "application/json"}


def api(u):
    r = urllib.request.Request(u, headers=H)
    try:
        with urllib.request.urlopen(r, timeout=150) as x:
            return json.loads(x.read())
    except urllib.error.HTTPError as e:
        return {"err": e.code}
    except Exception as e:
        return {"err": str(e)[:100]}


print("=== PROPERTI GSC (yang jadi pemilik/penuh) ===")
d = api("https://www.googleapis.com/webmasters/v3/sites")
gsc = []
for s in (d.get("siteEntry") or []):
    lvl = s.get("permissionLevel")
    tulis = lvl in ("siteOwner", "siteFullUser")
    gsc.append((s["siteUrl"], lvl))
    print(f"   {'✅' if tulis else '⚠️'} {s['siteUrl']:<50} {lvl}")

print("\n=== PROPERTI GA4 ===")
d = api("https://analyticsadmin.googleapis.com/v1beta/accountSummaries?pageSize=100")
ga4 = []
for acc in (d.get("accountSummaries") or []):
    for p in acc.get("propertySummaries", []):
        pid = p["property"].split("/")[-1]
        ga4.append((pid, p.get("displayName")))
        print(f"   {pid:<12} {p.get('displayName')}")

json.dump({"gsc": gsc, "ga4": ga4},
          open("/home/mantapman/.hermes/profiles/atun/workspace/drafts/peta_properti.json", "w"),
          indent=1, ensure_ascii=False)
print("\n→ drafts/peta_properti.json")
