#!/usr/bin/env python3
"""Simpan kunci PageSpeed (izin 600) dan uji ke PageSpeed Insights + CrUX API."""
import json, os, time, urllib.error, urllib.parse, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BERKAS = f"{WS}/.psi_api_key.json"
KUNCI = "AIzaSyAMzsbGYNwqgd8nzOZJLHvcKyHbK2HVXsM"

print("=== 1. simpan ===")
lama = None
if os.path.exists(BERKAS):
    try:
        lama = json.load(open(BERKAS)).get("key")
    except Exception:
        lama = None
if lama != KUNCI:
    with open(BERKAS, "w") as f:
        json.dump({"key": KUNCI, "disimpan": "2026-10-06", "sumber": "Bos (Telegram)",
                   "dipakai_untuk": ["PageSpeed Insights API", "CrUX API"]}, f, indent=1)
    os.chmod(BERKAS, 0o600)
    print(f"   {'diperbarui' if lama else 'disimpan'}: {BERKAS} (izin 600)")
else:
    print("   sudah ada, tidak berubah")

print("\n=== 2. uji PageSpeed Insights (klien: tslaw.id sebagai contoh) ===")
u = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?" + urllib.parse.urlencode(
    {"url": "https://www.tslaw.id/", "strategy": "mobile", "key": KUNCI, "category": "performance"})
try:
    t0 = time.time()
    r = urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"}), timeout=280)
    d = json.loads(r.read())
    lr = d.get("lighthouseResult", {})
    skor = {k: round((v.get("score") or 0) * 100) for k, v in lr.get("categories", {}).items()}
    print(f"   ✅ status {r.status} | {time.time()-t0:.1f} detik | skor: {skor}")
    for k in ("first-contentful-paint", "largest-contentful-paint", "total-blocking-time", "cumulative-layout-shift"):
        a = lr.get("audits", {}).get(k, {})
        if a:
            print(f"      {a.get('title', k):<34} {a.get('displayValue')}")
except urllib.error.HTTPError as e:
    print(f"   ❌ HTTP {e.code} | {e.read().decode('utf-8','replace')[:200]}")
except Exception as e:
    print(f"   ❌ {str(e)[:100]}")

print("\n=== 3. uji CrUX API (kecepatan pengguna nyata) ===")
cu = "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=" + KUNCI
for target in ({"origin": "https://www.tslaw.id"}, {"origin": "https://studiosoft.id"}):
    try:
        r = urllib.request.urlopen(urllib.request.Request(
            cu, data=json.dumps(target).encode(),
            headers={"Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}), timeout=90)
        d = json.loads(r.read())
        m = d.get("record", {}).get("metrics", {})
        print(f"\n   ✅ {target['origin']}")
        for nama_metrik in ("largest_contentful_paint", "cumulative_layout_shift", "interaction_to_next_paint"):
            mm = m.get(nama_metrik, {})
            if mm:
                print(f"      {nama_metrik:<28} p75 = {mm.get('percentiles', {}).get('p75')}")
        if not m:
            print("      (data tidak tersedia untuk origin ini)")
    except urllib.error.HTTPError as e:
        print(f"\n   ⚠️  {target['origin']} → HTTP {e.code} | {e.read().decode('utf-8','replace')[:150]}")
    except Exception as e:
        print(f"\n   ❌ {target['origin']} → {str(e)[:80]}")
