#!/usr/bin/env python3
"""Telusuri penyebab 401 pada token Ahrefs: uji beberapa endpoint & cara kirim token."""
import json, urllib.parse, urllib.request, urllib.error

TOKEN = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/.ahrefs_token.json"))["token"]
print(f"panjang token: {len(TOKEN)} karakter | awal: {TOKEN[:6]}… akhir: …{TOKEN[-4:]}")

VARIAN = [
    ("Bearer (v3)", {"Authorization": f"Bearer {TOKEN}"}),
    ("header x-api-key", {"x-api-key": TOKEN}),
    ("query param token", {}),
    ("Authorization mentah", {"Authorization": TOKEN}),
]
JALUR = [
    ("limits-and-usage", "https://api.ahrefs.com/v3/subscription-info/limits-and-usage"),
    ("backlinks-stats", "https://api.ahrefs.com/v3/site-explorer/backlinks-stats?"
                        + urllib.parse.urlencode({"target": "studiosoft.id", "date": "2026-10-01", "mode": "domain"})),
]

for nama, u in JALUR:
    print(f"\n=== {nama} ===")
    for label, h in VARIAN:
        alamat = u + (f"&token={TOKEN}" if "query param" in label else "")
        try:
            r = urllib.request.urlopen(urllib.request.Request(alamat, headers={"Accept": "application/json", **h}), timeout=60)
            print(f"   ✅ {label:<22} status {r.status} → {r.read().decode()[:200]}")
        except urllib.error.HTTPError as e:
            badan = e.read().decode("utf-8", "replace")[:200]
            tambahan = ""
            for k in ("x-ratelimit-limit", "www-authenticate", "x-ahrefs-error"):
                if e.headers.get(k):
                    tambahan += f" | {k}={e.headers.get(k)}"
            print(f"   ❌ {label:<22} HTTP {e.code} → {badan}{tambahan}")
        except Exception as e:
            print(f"   ❌ {label:<22} {str(e)[:70]}")

print("\n=== apakah domain api-nya benar? ===")
for u in ("https://api.ahrefs.com/", "https://api.ahrefs.com/v3/", "https://docs.ahrefs.com/"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"}), timeout=45)
        print(f"   {r.status} | {u} | {r.read().decode('utf-8','replace')[:120]}")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} | {u}")
    except Exception as e:
        print(f"   gagal {str(e)[:60]} | {u}")
