#!/usr/bin/env python3
"""Simpan kunci Serper.dev (izin 600) dan uji hasil pencarian Google untuk kata kunci klien."""
import json, os, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BERKAS = f"{WS}/.serper_token.json"
KUNCI = "0b75ddc9d3a0eb55e0dc109b3e0a495f1251528d"

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)",
                   "layanan": "Serper.dev — hasil pencarian Google via API"}, f, indent=1)
    os.chmod(BERKAS, 0o600)
    print(f"   {'diperbarui' if lama else 'disimpan'}: {BERKAS} (izin 600)")
else:
    print("   sudah ada")

H = {"X-API-KEY": KUNCI, "Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}


def cari(q, lokasi="id", bahasa="id", jumlah=10):
    body = json.dumps({"q": q, "gl": lokasi, "hl": bahasa, "num": jumlah}).encode()
    t0 = time.time()
    try:
        r = urllib.request.urlopen(urllib.request.Request("https://google.serper.dev/search", data=body, headers=H), timeout=90)
        return r.status, json.loads(r.read()), time.time() - t0
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:250], time.time() - t0
    except Exception as e:
        return 0, str(e)[:100], time.time() - t0


UJI = ["jasa seo surabaya", "digital agency surabaya", "jasa digital marketing surabaya"]
for q in UJI:
    st, d, detik = cari(q)
    print(f"\n=== «{q}» | status {st} | {detik:.1f} detik ===")
    if st != 200 or not isinstance(d, dict):
        print("   ", str(d)[:200])
        continue
    # AI Overview kalau ada
    if d.get("aiOverview"):
        teks = json.dumps(d["aiOverview"], ensure_ascii=False)
        print(f"   ⚡ AI OVERVIEW ada ({len(teks)} karakter)")
    if d.get("answerBox"):
        print("   ⚡ Answer box ada")
    for i, hasil in enumerate((d.get("organic") or [])[:6], 1):
        print(f"   {i}. {str(hasil.get('title'))[:78]}")
        print(f"      {str(hasil.get('link'))[:88]}")
    if d.get("relatedSearches"):
        print("   terkait:", [x.get("query") for x in d["relatedSearches"][:5]])
