#!/usr/bin/env python3
"""Ukur PageSpeed Insights (mobile) untuk halaman terpilih. Angka nyata dari API."""
import json, sys, time, urllib.error, urllib.parse, urllib.request

KEY = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/.psi_api_key.json"))["key"]
URLS = sys.argv[1:] or ["https://studiosoft.id/"]

for u in URLS:
    q = urllib.parse.urlencode({"url": u, "strategy": "mobile", "key": KEY, "category": "performance"})
    api = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?" + q
    try:
        t0 = time.time()
        r = urllib.request.urlopen(urllib.request.Request(api, headers={"User-Agent": "Mozilla/5.0"}), timeout=300)
        d = json.loads(r.read())
        lr = d.get("lighthouseResult", {})
        skor = round((lr.get("categories", {}).get("performance", {}).get("score") or 0) * 100)
        print(f"{u} | HTTP {r.status} | {time.time()-t0:.0f}s | skor performa mobile: {skor}")
        print(f"  field data (CrUX): {json.dumps(d.get('loadingExperience', {}).get('metrics', {}), ensure_ascii=False)[:400]}")
        for k in ("first-contentful-paint", "largest-contentful-paint", "total-blocking-time",
                  "cumulative-layout-shift", "speed-index", "interactive"):
            a = (lr.get("audits") or {}).get(k) or {}
            if a:
                print(f"  {a.get('title', k)}: {a.get('displayValue')}")
        for a in sorted(lr.get("audits", {}).values(), key=lambda x: x.get("score") or 2):
            if a.get("score") is not None and a["score"] < 0.9 and a.get("details", {}).get("type") == "opportunity":
                print(f"  celah: {a.get('title')} → {a.get('displayValue')}")
        json.dump(d, open("/home/mantapman/.hermes/profiles/atun/workspace/psi_hasil_artikel.json", "w"))
    except urllib.error.HTTPError as e:
        print(f"{u} | GAGAL HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:200]}")
    except Exception as e:
        print(f"{u} | GAGAL: {type(e).__name__}: {e}")
