#!/usr/bin/env python3
"""Uji kunci Semrush TSC pada beberapa bentuk permintaan (kunci tidak dicetak)."""
import json, urllib.error, urllib.parse, urllib.request

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

UJI = [
    ("/ domain_rank", "https://api.semrush.com/",
     {"type": "domain_rank", "domain": "theskincodeclinic.com", "database": "id"}),
    ("/ phrase_this", "https://api.semrush.com/",
     {"type": "phrase_this", "phrase": "dokter kulit sidoarjo", "database": "id"}),
    ("/ phrase_organic", "https://api.semrush.com/",
     {"type": "phrase_organic", "phrase": "klinik kecantikan krian", "database": "id", "display_limit": "5",
      "export_columns": "Dn,Ur"}),
    ("/v1 phrase_this", "https://api.semrush.com/analytics/v1/",
     {"type": "phrase_this", "phrase": "dokter kulit sidoarjo", "database": "id"}),
    ("/v1 domain_organic", "https://api.semrush.com/analytics/v1/",
     {"type": "domain_organic", "domain": "theskincodeclinic.com", "database": "id",
      "display_limit": "5", "export_columns": "Ph,Po,Nq"}),
    ("/v3 phrase_this", "https://api.semrush.com/analytics/v3/",
     {"type": "phrase_this", "phrase": "dokter kulit sidoarjo", "database": "id"}),
    ("/trends", "https://api.semrush.com/analytics/trends/v1/",
     {"type": "phrase_this", "phrase": "dokter kulit", "database": "id"}),
]

for nama, dasar, param in UJI:
    url = dasar + "?" + 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").strip()
        baris = t.splitlines()
        print(f"✅ {nama:<20} HTTP {x.status} · {len(baris)} baris")
        for b in baris[:3]:
            print(f"       {b[:120]}")
    except urllib.error.HTTPError as e:
        print(f"❌ {nama:<20} HTTP {e.code} · {e.read().decode('utf-8','replace').strip()[:110]}")
    except Exception as e:
        print(f"❌ {nama:<20} {str(e)[:80]}")
