#!/usr/bin/env python3
"""Simpan kunci Otterly + cari bentuk API-nya lewat dokumentasi, lalu uji."""
import html as H, json, os, re, stat, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BERKAS = f"{WS}/.otterly_token.json"
KUNCI = "oai_live_9c2d1c806e9fc91ef4f22e031a54ca178a20a6552e0f002e8a7099595d105b39074693e4"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}

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": "Otterly.ai — pemantauan visibilitas di jawaban AI"}, f, indent=1)
    os.chmod(BERKAS, 0o600)
    print(f"   {'diperbarui' if lama else 'disimpan'}: {BERKAS} (izin 600)")
else:
    print("   sudah ada")

print(f"   bentuk kunci: {KUNCI[:9]}… ({len(KUNCI)} karakter)")

print("\n=== 2. cari dokumentasi API Otterly ===")
KANDIDAT = ["https://otterly.ai/docs", "https://docs.otterly.ai/", "https://otterly.ai/api",
            "https://api.otterly.ai/", "https://app.otterly.ai/api-docs", "https://otterly.ai/pricing"]
for u in KANDIDAT:
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=40)
        h = r.read().decode("utf-8", "replace")
        print(f"\n   ✅ {u} | {r.status} | {len(h):,} byte")
        teks = H.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", h)))
        for pola in (r"https://api\.otterly\.ai[^\s\"'<>]{0,90}", r"(?:Bearer|api[_-]?key|X-API-Key)[^\s\"'<>]{0,60}",
                     r"GET /v\d[^\s\"'<>]{0,60}"):
            for t in sorted(set(re.findall(pola, teks, re.I)))[:4]:
                print("      •", t[:140])
    except urllib.error.HTTPError as e:
        print(f"   ⚠️  {u} → HTTP {e.code}")
    except Exception as e:
        print(f"   ❌ {u} → {str(e)[:50]}")
