#!/usr/bin/env python3
"""Otterly: lihat laporan merek yang sudah ada (dan isinya kalau ada)."""
import json, urllib.error, urllib.request

KUNCI = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/.otterly_token.json"))["key"]
BASE = "https://data.otterly.ai"
H = {"Authorization": f"Bearer {KUNCI}", "Accept": "application/json", "User-Agent": "Mozilla/5.0"}


def panggil(jalur, metode="GET", data=None, timeout=90):
    body = json.dumps(data).encode() if data is not None else None
    h = dict(H)
    if body:
        h["Content-Type"] = "application/json"
    try:
        r = urllib.request.urlopen(urllib.request.Request(BASE + jalur, data=body, headers=h, method=metode), timeout=timeout)
        return r.status, r.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:200]
    except Exception as e:
        return 0, str(e)[:80]


print("=== laporan merek yang sudah ada ===")
st, isi = panggil("/v1/reports/brand")
print(f"   status {st}")
if st == 200:
    try:
        d = json.loads(isi)
        items = d.get("items") or d.get("data") or (d if isinstance(d, list) else [])
        print(f"   jumlah: {len(items)}")
        for it in items[:10]:
            print(f"      {json.dumps(it, ensure_ascii=False)[:400]}")
    except Exception as e:
        print("   ", isi[:400])

print("\n=== jika ada, lihat statistiknya ===")
try:
    d = json.loads(isi)
    items = d.get("items") or d.get("data") or []
    for it in items[:2]:
        rid = it.get("id") or it.get("_id") or it.get("reportId")
        if not rid:
            continue
        for jalur in (f"/v1/reports/brand/{rid}/stats", f"/v1/reports/brand/{rid}/prompts"):
            st2, isi2 = panggil(jalur, timeout=60)
            print(f"   {st2} | {jalur[-46:]} | {isi2[:260]}")
except Exception as e:
    print("   (tidak bisa membaca daftar)", str(e)[:80])
