#!/usr/bin/env python3
"""Ambil contoh pemakaian API dari dokumentasi Otterly (blok kode) untuk memastikan formatnya."""
import html as H, json, re, urllib.error, urllib.request

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}
KUNCI = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/.otterly_token.json"))["key"]

for u in ("https://docs.otterly.ai/", "https://docs.otterly.ai/api/", "https://docs.otterly.ai/getting-started/",
          "https://docs.otterly.ai/api-reference/"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60)
        h = r.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        print(f"\n=== {u} → HTTP {e.code}")
        continue
    except Exception as e:
        print(f"\n=== {u} → {str(e)[:60]}")
        continue
    teks = H.unescape(re.sub(r"<[^>]+>", " ", h))
    teks = re.sub(r"\s+", " ", teks)
    print(f"\n=== {u} | {len(h):,} byte ===")
    for pola in (r"curl[^.]{0,240}", r"https://api\.otterly\.ai[^\s\"'<>]{0,80}",
                 r"[^.]{0,80}(?:x-api-key|X-API-KEY|api_key|Bearer)[^.]{0,120}",
                 r"GET /v1/[a-z0-9\-/_{}]{0,40}"):
        temuan = sorted(set(re.findall(pola, teks, re.I)))[:6]
        for t in temuan:
            print("   •", t.strip()[:230])

print("\n=== uji ulang dengan beberapa bentuk header ===")
KANDIDAT = [
    ("Bearer", {"Authorization": f"Bearer {KUNCI}"}),
    ("x-api-key", {"x-api-key": KUNCI}),
    ("X-API-Key", {"X-API-Key": KUNCI}),
    ("api-key", {"api-key": KUNCI}),
    ("Authorization mentah", {"Authorization": KUNCI}),
]
for nama, h in KANDIDAT:
    for base in ("https://api.otterly.ai", "https://app.otterly.ai"):
        try:
            r = urllib.request.urlopen(urllib.request.Request(f"{base}/v1/health",
                                                              headers={"Accept": "application/json", "User-Agent": "Mozilla/5.0", **h}), timeout=45)
            print(f"   ✅ {nama:<20} {base:<26} status {r.status} → {r.read().decode()[:120]}")
        except urllib.error.HTTPError as e:
            print(f"   ❌ {nama:<20} {base:<26} HTTP {e.code} → {e.read().decode('utf-8','replace')[:90]}")
        except Exception as e:
            print(f"   ❌ {nama:<20} {base:<26} {str(e)[:60]}")
