#!/usr/bin/env python3
"""Baca dokumentasi Otterly: ambil base URL, cara auth, dan daftar endpoint."""
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"]


def ambil(u, timeout=60):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=timeout)
        return r.status, r.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, ""
    except Exception as e:
        return 0, str(e)[:80]


print("=== halaman api-docs ===")
st, h = ambil("https://app.otterly.ai/api-docs")
print(f"   status {st} | {len(h):,} byte")
if h:
    # Swagger UI biasanya memuat spec dari file json
    for m in re.findall(r'(?:url|spec-url|src)\s*[=:]\s*["\']([^"\']*\.(?:json|yaml))["\']', h, re.I):
        print("      spec:", m)
    for m in sorted(set(re.findall(r"https://api\.otterly\.ai[^\s\"'<>]{0,80}", h)))[:6]:
        print("      base:", m)
    for m in sorted(set(re.findall(r"/api/v\d/[a-z0-9\-/_{}]{2,50}", h, re.I)))[:20]:
        print("      endpoint:", m)

print("\n=== coba spec yang mungkin ===")
for u in ("https://app.otterly.ai/api-docs/openapi.json", "https://app.otterly.ai/openapi.json",
          "https://api.otterly.ai/openapi.json", "https://app.otterly.ai/api/openapi.json"):
    st2, h2 = ambil(u, timeout=40)
    print(f"   {st2} | {u} | {len(h2)} byte")
    if st2 == 200 and h2.strip().startswith("{"):
        try:
            spec = json.loads(h2)
            print("      judul:", spec.get("info", {}).get("title"))
            print("      server:", spec.get("servers"))
            jalur = list((spec.get("paths") or {}).keys())[:15]
            for j in jalur:
                print("      ·", j)
        except Exception as e:
            print("      (bukan JSON valid)", str(e)[:60])

print("\n=== dokumentasi resmi docs.otterly.ai ===")
st3, h3 = ambil("https://docs.otterly.ai/")
teks = H.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", h3)))
for pola in (r"https://api\.otterly\.ai[^\s\"'<>]{0,90}", r"[^.]{0,110}(?:Bearer|Authorization)[^.]{0,140}\.",
             r"/v\d/[a-z0-9\-/_{}]{2,40}"):
    for t in sorted(set(re.findall(pola, teks, re.I)))[:6]:
        print("   •", re.sub(r"\s+", " ", t)[:190])
