#!/usr/bin/env python3
"""Uji kunci Semrush pada API versi baru (Bearer) — API lama menolak dengan 'WRONG KEY - ID PAIR'."""
import json, urllib.parse, urllib.request, urllib.error

KUNCI = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/.semrush_token.json"))["token"]
print(f"kunci: {len(KUNCI)} karakter | awal {KUNCI[:7]}…")

VARIAN = [
    ("Bearer", {"Authorization": f"Bearer {KUNCI}"}),
    ("key header", {"X-API-KEY": KUNCI}),
]
JALUR = [
    ("v3 report", "https://api.semrush.com/analytics/v1/report?"
                  + urllib.parse.urlencode({"report": "domain_overview", "target": "studiosoft.id",
                                            "database": "id"})),
    ("v3 metrics", "https://api.semrush.com/v3/site-explorer/metrics?"
                   + urllib.parse.urlencode({"target": "studiosoft.id", "database": "id"})),
    ("v3 root", "https://api.semrush.com/v3/"),
    ("legacy analog", "https://api.semrush.com/analytics/v1/?" + urllib.parse.urlencode(
        {"type": "domain_ranks", "export_columns": "Dn,Rk,Or", "domain": "studiosoft.id", "database": "id"})),
]

for nama, u in JALUR:
    for label, h in VARIAN:
        u2 = u + ("&key=" + KUNCI if "key header" in label else "")
        try:
            r = urllib.request.urlopen(urllib.request.Request(u2, headers={"Accept": "application/json", **h}), timeout=60)
            print(f"   ✅ {nama:<14} {label:<11} status {r.status} → {r.read().decode()[:220]}")
        except urllib.error.HTTPError as e:
            print(f"   ❌ {nama:<14} {label:<11} HTTP {e.code} → {e.read().decode('utf-8','replace')[:160]}")
        except Exception as e:
            print(f"   ❌ {nama:<14} {label:<11} {str(e)[:80]}")

print("\n=== dokumentasi Semrush (kalau terjangkau) ===")
for u in ("https://developer.semrush.com/api/v3/", "https://www.semrush.com/api-documentation/",
          "https://developer.semrush.com/"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent": "Mozilla/5.0"}), timeout=45)
        print(f"   {r.status} | {u} | {len(r.read()):,} byte")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} | {u}")
    except Exception as e:
        print(f"   gagal {str(e)[:60]} | {u}")
