#!/usr/bin/env python3
"""Uji kunci Semrush yang tersimpan dengan bentuk permintaan yang benar (v3 klasik)."""
import json, urllib.error, urllib.parse, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
KEY = json.load(open(f"{WS}/.semrush_token.json"))["token"]
UA = {"User-Agent": "Mozilla/5.0"}

UJI = [
    ("domain_rank", {"type": "domain_rank", "domain": "theskincodeclinic.com", "database": "id"}),
    ("phrase_this", {"type": "phrase_this", "phrase": "dokter kulit sidoarjo", "database": "id"}),
    ("domain_organic", {"type": "domain_organic", "domain": "theskincodeclinic.com", "database": "id",
                        "display_limit": "5", "export_columns": "Ph,Po,Pp,Nq,Cp,Ur"}),
    ("phrase_organic", {"type": "phrase_organic", "phrase": "dokter kulit krian", "database": "id",
                        "display_limit": "5", "export_columns": "Dn,Ur"}),
    ("phrase_kdi", {"type": "phrase_kdi", "phrase": "klinik kecantikan krian", "database": "id"}),
]

for nama, param in UJI:
    param = dict(param)
    url = "https://api.semrush.com/?" + urllib.parse.urlencode({**param, "key": KEY})
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60) as x:
            t = x.read().decode("utf-8", "replace")
        baris = t.strip().splitlines()
        print(f"✅ {nama:<16} HTTP {x.status} · {len(baris)} baris")
        for b in baris[:3]:
            print(f"      {b[:110]}")
    except urllib.error.HTTPError as e:
        print(f"❌ {nama:<16} HTTP {e.code} · {e.read().decode('utf-8','replace')[:90]}")
    except Exception as e:
        print(f"❌ {nama:<16} {str(e)[:70]}")
